Example usage for javax.swing JFileChooser showDialog

List of usage examples for javax.swing JFileChooser showDialog

Introduction

In this page you can find the example usage for javax.swing JFileChooser showDialog.

Prototype

@SuppressWarnings("deprecation")
public int showDialog(Component parent, String approveButtonText) throws HeadlessException 

Source Link

Document

Pops a custom file chooser dialog with a custom approve button.

Usage

From source file:jhplot.HChart.java

/**
 * Exports the image to some graphic format.
 *///  w  w w.j a va  2s .  co m
protected void exportImage() {

    if (isBorderShown())
        showBorders(false);

    JFrame jm = getFrame();
    JFileChooser fileChooser = jhplot.gui.CommonGUI.openImageFileChooser(jm);

    if (fileChooser.showDialog(jm, "Save As") == 0) {

        final File scriptFile = fileChooser.getSelectedFile();
        if (scriptFile == null)
            return;
        else if (scriptFile.exists()) {
            int res = JOptionPane.showConfirmDialog(jm, "The file exists. Do you want to overwrite the file?",
                    "", JOptionPane.YES_NO_OPTION);
            if (res == JOptionPane.NO_OPTION)
                return;
        }
        String mess = "write image  file ..";
        JHPlot.showStatusBarText(mess);
        Thread t = new Thread(mess) {
            public void run() {
                export(scriptFile.getAbsolutePath());
            };
        };
        t.start();
    }

}

From source file:pcd3.View.java

private void pilihGambarSharpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarSharpMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;//from   w  w w .  j a  v a2 s .c  o  m
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitraTelu.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormTelu.setImage(bimg);
                    imageFormTelu.imageToGray(1);
                    citraSharpheningAwal.setText("");
                    citraSharpheningGray.setText("");
                    citraSharpheningHasil.setText("");
                    citraSharpheningAwal.setIcon(new ImageIcon(bimg.getScaledInstance(300, 300, 0)));
                    citraSharpheningGray.setIcon(
                            new ImageIcon(imageFormTelu.getGrayImage().getScaledInstance(300, 300, 0)));
                    ukuranCitraTelu.setText("Ukuran Citra : " + imageFormTelu.getTinggi() + " x "
                            + imageFormTelu.getLebar() + "");
                    imageFormTelu.setSharpeningImage();
                    citraSharpheningHasil.setIcon(
                            new ImageIcon(imageFormTelu.getSharpeningImage().getScaledInstance(300, 300, 0)));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}

From source file:pcd3.View.java

private void pilihGambarLoroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarLoroMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;/*  w ww . ja  v  a2s  .c  om*/
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitraLoro.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormLoro.setImage(bimg);
                    imageFormLoro.imageToGray(1);
                    citraSmoothingAwal.setText("");
                    citraSmoothingGray.setText("");
                    citraSmoothingHasil.setText("");
                    citraSmoothingAwal.setIcon(new ImageIcon(bimg.getScaledInstance(300, 300, 0)));
                    citraSmoothingGray.setIcon(
                            new ImageIcon(imageFormLoro.getGrayImage().getScaledInstance(300, 300, 0)));
                    ukuranCitraLoro.setText("Ukuran Citra : " + imageFormLoro.getTinggi() + " x "
                            + imageFormLoro.getLebar() + "");
                    imageFormLoro.setSmoothingImage();
                    citraSmoothingHasil.setIcon(
                            new ImageIcon(imageFormLoro.getSmoothingImage().getScaledInstance(300, 300, 0)));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}

From source file:pcd3.View.java

private void pilihGambarCitraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarCitraMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;/*ww w . ja va2s. c  o  m*/
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitra.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormSiji.setImage(bimg);
                    imageFormSiji.imageToGray(1);
                    imageFormSiji.setHistogram();
                    int jumlah = 0;
                    DefaultCategoryDataset chartBarAwal = new DefaultCategoryDataset();
                    DefaultCategoryDataset chartBarHasil = new DefaultCategoryDataset();
                    //barChartData.setva
                    for (int i = 0; i < imageFormSiji.getHistogram().size(); i++) {
                        System.out.println(imageFormSiji.getHistogram().get(i).getRgb() + " = "
                                + imageFormSiji.getHistogram().get(i).getJumlah() + " = "
                                + imageFormSiji.getHistogram().get(i).getJumlahKumulatif() + " = "
                                + imageFormSiji.getHistogram().get(i).getHasilEkualisasi());
                        jumlah += imageFormSiji.getHistogram().get(i).getJumlah();
                        chartBarAwal.setValue(imageFormSiji.getHistogram().get(i).getJumlah(), "aha",
                                "" + imageFormSiji.getHistogram().get(i).getRgb());
                        chartBarHasil.setValue(imageFormSiji.getHistogram().get(i).getHasilEkualisasi(), "aha",
                                "" + imageFormSiji.getHistogram().get(i).getRgb());
                    }

                    JFreeChart chartSiji = ChartFactory.createBarChart("Histogam Citra Awal", "RGB", "Jumlah",
                            chartBarAwal, PlotOrientation.VERTICAL, false, true, false);
                    JFreeChart chartLoro = ChartFactory.createBarChart("Histogram Citra Ekualisasi", "RGB",
                            "Jumlah", chartBarHasil, PlotOrientation.VERTICAL, false, true, false);
                    CategoryPlot categoryPlotSiji = chartSiji.getCategoryPlot();
                    CategoryPlot categoryPlotLoro = chartLoro.getCategoryPlot();
                    categoryPlotSiji.setRangeGridlinePaint(Color.orange);
                    categoryPlotLoro.setRangeGridlinePaint(Color.orange);

                    ChartPanel cpanelSiji = new ChartPanel(chartSiji);
                    ChartPanel cpanelLoro = new ChartPanel(chartLoro);
                    chartAwal.removeAll();
                    chartAwal.add(cpanelSiji);
                    chartAwal.validate();

                    chartEkualisasi.removeAll();
                    chartEkualisasi.add(cpanelLoro);
                    chartEkualisasi.validate();

                    System.out.println("Jumlah = " + jumlah);
                    citraLabel.setText("");
                    citraGrayLabel.setText("");
                    citraEkualisasi.setText("");
                    citraLabel.setIcon(new ImageIcon(bimg.getScaledInstance(230, 230, 0)));
                    //resetCitra();
                    ukuranCitra.setText("Ukuran Citra : " + imageFormSiji.getTinggi() + " x "
                            + imageFormSiji.getLebar() + "");
                    imageFormSiji.setSmoothingImage();
                    imageFormSiji.setSharpeningImage();
                    citraEkualisasi.setIcon(
                            new ImageIcon(imageFormSiji.getEqualImage().getScaledInstance(230, 230, 0)));
                    citraGrayLabel.setIcon(
                            new ImageIcon(imageFormSiji.getGrayImage().getScaledInstance(230, 230, 0)));
                    citraSmoothingHasil.setIcon(new ImageIcon(imageFormSiji.getSmoothingImage()));
                    citraSharpheningHasil.setIcon(new ImageIcon(imageFormSiji.getSharpeningImage()));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}

From source file:lu.fisch.moenagade.model.Project.java

public void openSound(Frame frame) {
    JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File(lastOpenedSound));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new FileFilter() {
        @Override/*  www. j a  v  a  2  s .co  m*/
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("wav")) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            return "Supported sound files (*.wav)";
        }
    });
    int returnVal = fc.showDialog(frame, "Add sound");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loadSound(fc.getSelectedFile());
    }

}

From source file:canreg.client.gui.dataentry.PDSEditorInternalFrame.java

@Action
public void savePNGAction() {
    if (chart != null) {
        JFileChooser chooser = new JFileChooser();
        FileFilter filter = new FileFilter() {

            @Override/*from  w w w  .j a  va 2s .  co  m*/
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith("png"); //NOI18N
            }

            @Override
            public String getDescription() {
                return java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("PNG GRAPHICS FILES");
            }
        };
        chooser.setFileFilter(filter);
        int result = chooser.showDialog(this,
                java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("CHOOSE FILENAME"));
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                File file = chooser.getSelectedFile();
                if (!file.getName().toLowerCase().endsWith("png")) { //NOI18N
                    file = new File(file.getAbsolutePath() + ".png"); //NOI18N
                }
                ChartUtilities.saveChartAsPNG(file, chart, pyramidPanelHolder.getWidth(),
                        pyramidPanelHolder.getHeight());
            } catch (IOException ex) {
                Logger.getLogger(PDSEditorInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:canreg.client.gui.dataentry.PDSEditorInternalFrame.java

@Action
public void saveSVGAction() {
    if (chart != null) {
        JFileChooser svgFileChooser = new JFileChooser();
        FileFilter filter = new FileFilter() {

            @Override//from ww w  .  j  a  va2  s.co m
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith("svg"); //NOI18N
            }

            @Override
            public String getDescription() {
                return java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("SVG GRAPHICS FILES");
            }
        };
        svgFileChooser.setFileFilter(filter);
        int result = svgFileChooser.showDialog(this,
                java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("CHOOSE FILENAME"));
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                File file = svgFileChooser.getSelectedFile();
                if (!file.getName().toLowerCase().endsWith("svg")) { //NOI18N
                    file = new File(file.getAbsolutePath() + ".svg"); //NOI18N
                }
                canreg.client.analysis.Tools.exportChartAsSVG(chart,
                        new Rectangle(pyramidPanelHolder.getWidth(), pyramidPanelHolder.getHeight()), file);
            } catch (IOException ex) {
                Logger.getLogger(PDSEditorInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:lu.fisch.moenagade.model.Project.java

public void openImage(Frame frame) {
    JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File(lastOpenedImage));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new FileFilter() {
        @Override/*from ww w  .j  a  v a  2s  . co m*/
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg")) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            return "Supported image files (*.jpg, *.png)";
        }
    });
    int returnVal = fc.showDialog(frame, "Add image");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loadImage(fc.getSelectedFile());
    }

}

From source file:model.settings.ReadSettings.java

/**
 * checks whether program information on current workspace exist.
 * @return if workspace is now set./*from   w  w w. j av  a2 s . c o m*/
 */
public static String install() {
    boolean installed = false;
    String wsLocation = "";
    /*
     * does program root directory exist?
     */
    if (new File(PROGRAM_LOCATION).exists()) {

        //try to read 
        try {
            wsLocation = readFromFile(PROGRAM_SETTINGS_LOCATION);

            installed = new File(wsLocation).exists();
            if (!installed) {
                wsLocation = "";
            }

        } catch (FileNotFoundException e) {
            System.out.println("file not found " + e);
            showErrorMessage();
        } catch (IOException e) {
            System.out.println("io" + e);
            showErrorMessage();
        }
    }

    //if settings not found.
    if (!installed) {

        new File(PROGRAM_LOCATION).mkdir();
        try {

            //create new file chooser
            JFileChooser jc = new JFileChooser();

            //sets the text and language of all the components in JFileChooser
            UIManager.put("FileChooser.openDialogTitleText", "Open");
            UIManager.put("FileChooser.lookInLabelText", "LookIn");
            UIManager.put("FileChooser.openButtonText", "Open");
            UIManager.put("FileChooser.cancelButtonText", "Cancel");
            UIManager.put("FileChooser.fileNameLabelText", "FileName");
            UIManager.put("FileChooser.filesOfTypeLabelText", "TypeFiles");
            UIManager.put("FileChooser.openButtonToolTipText", "OpenSelectedFile");
            UIManager.put("FileChooser.cancelButtonToolTipText", "Cancel");
            UIManager.put("FileChooser.fileNameHeaderText", "FileName");
            UIManager.put("FileChooser.upFolderToolTipText", "UpOneLevel");
            UIManager.put("FileChooser.homeFolderToolTipText", "Desktop");
            UIManager.put("FileChooser.newFolderToolTipText", "CreateNewFolder");
            UIManager.put("FileChooser.listViewButtonToolTipText", "List");
            UIManager.put("FileChooser.newFolderButtonText", "CreateNewFolder");
            UIManager.put("FileChooser.renameFileButtonText", "RenameFile");
            UIManager.put("FileChooser.deleteFileButtonText", "DeleteFile");
            UIManager.put("FileChooser.filterLabelText", "TypeFiles");
            UIManager.put("FileChooser.detailsViewButtonToolTipText", "Details");
            UIManager.put("FileChooser.fileSizeHeaderText", "Size");
            UIManager.put("FileChooser.fileDateHeaderText", "DateModified");
            SwingUtilities.updateComponentTreeUI(jc);

            jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jc.setMultiSelectionEnabled(false);

            final String informationMsg = "Please select the workspace folder. \n"
                    + "By default, the new files are saved in there. \n\n"
                    + "Is changed simply by using the Save-As option.\n"
                    + "If no folder is specified, the default worspace folder \n"
                    + "is the home directory of the current user.";
            final int response = JOptionPane.showConfirmDialog(jc, informationMsg, "Select workspace folder",
                    JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);

            final String defaultSaveLocation = System.getProperty("user.home")
                    + System.getProperty("file.separator");
            File f;
            if (response != JOptionPane.NO_OPTION) {

                //fetch selected file
                f = jc.getSelectedFile();
                jc.showDialog(null, "select");
            } else {
                f = new File(defaultSaveLocation);
            }

            printInformation();

            if (f == null) {
                f = new File(defaultSaveLocation);
            }
            //if file selected
            if (f != null) {

                //if the file exists
                if (f.exists()) {
                    writeToFile(PROGRAM_SETTINGS_LOCATION, ID_PROGRAM_LOCATION + "\n" + f.getAbsolutePath());
                } else {

                    //open message dialog
                    JOptionPane.showConfirmDialog(null, "Folder does " + "not exist",
                            "Error creating workspace", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
                            null);
                }

                //recall install
                return install();
            }

        } catch (IOException e) {
            System.out.println(e);
            JOptionPane.showConfirmDialog(null, "An exception occured." + " Try again later.",
                    "Error creating workspace", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null);
        }
    }

    if (System.getProperty("os.name").equals("Mac OS X")) {

        installOSX();
    } else if (System.getProperty("os.name").equals("Linux")) {
        installLinux();
    } else if (System.getProperty("os.name").equals("Windows")) {
        installWindows();
    }

    return wsLocation;

}

From source file:org.jets3t.apps.cockpit.Cockpit.java

/**
 * Downloads the objects currently selected in the objects table. The user is
 * prompted//from w  w  w .j a v a2 s  .c o  m
 * Prepares to perform a download of objects from S3 by prompting the user for a directory
 * to store the files in, then performing the download.
 *
 * @throws IOException
 */
private void downloadSelectedObjects() {
    // Prompt user to choose directory location for downloaded files (or cancel download altogether)
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose directory to save S3 files in");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setSelectedFile(downloadDirectory);

    int returnVal = fileChooser.showDialog(ownerFrame, "Choose Directory");
    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;
    }

    downloadDirectory = fileChooser.getSelectedFile();

    boolean storeEmptyDirectories = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME)
            .getBoolProperty("uploads.storeEmptyDirectories", true);
    final Map<String, String> objectKeyToFilepathMap = FileComparer.getInstance()
            .buildObjectKeyToFilepathMap(downloadDirectory.listFiles(), "", storeEmptyDirectories);

    // Build map of S3 Objects being downloaded.
    final Map s3DownloadObjectsMap = FileComparer.getInstance().populateObjectMap("", getSelectedObjects());

    final HyperlinkActivatedListener hyperlinkListener = this;

    runInBackgroundThread(new Runnable() {
        public void run() {
            // Retrieve details of objects for download
            if (!retrieveObjectsDetails(getSelectedObjects())) {
                return;
            }

            try {
                final FileComparerResults comparisonResults = compareRemoteAndLocalFiles(objectKeyToFilepathMap,
                        s3DownloadObjectsMap);

                DownloadPackage[] downloadPackages = buildDownloadPackageList(comparisonResults,
                        s3DownloadObjectsMap);
                if (downloadPackages == null) {
                    return;
                }

                s3ServiceMulti.downloadObjects(currentSelectedBucket, downloadPackages);

            } catch (final Exception e) {
                runInDispatcherThreadImmediately(new Runnable() {
                    public void run() {
                        String message = "Unable to download objects";
                        log.error(message, e);
                        ErrorDialog.showDialog(ownerFrame, hyperlinkListener, message, e);
                    }
                });
            }
        }
    });
}