Example usage for javax.swing JFileChooser setSelectedFile

List of usage examples for javax.swing JFileChooser setSelectedFile

Introduction

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

Prototype

@BeanProperty(preferred = true)
public void setSelectedFile(File file) 

Source Link

Document

Sets the selected file.

Usage

From source file:com.opendoorlogistics.core.utils.ui.FileBrowserPanel.java

private static JButton createBrowseButton(final boolean directoriesOnly, final String browserApproveButtonText,
        final JTextField textField, final FileFilter... fileFilters) {
    JButton browseButton = new JButton("...");
    browseButton.addActionListener(new ActionListener() {

        @Override//from   w ww  .  j  a  va2s.  c  o  m
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();

            if (textField.getText() != null) {
                File file = new File(textField.getText());

                // if the file doesn't exist but the directory does, get that
                if (!file.exists() && file.getParentFile() != null && file.getParentFile().exists()) {
                    file = file.getParentFile();
                }

                if (!directoriesOnly && file.isFile()) {
                    chooser.setSelectedFile(file);
                }

                if (file.isDirectory() && file.exists()) {
                    chooser.setCurrentDirectory(file);
                }
            }

            if (directoriesOnly) {
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            }

            // add filters and automatically select correct one
            if (fileFilters.length == 1) {
                chooser.setFileFilter(fileFilters[0]);
            } else {
                for (FileFilter filter : fileFilters) {
                    chooser.addChoosableFileFilter(filter);
                    if (filter instanceof FileNameExtensionFilter) {
                        if (matchesFilter((FileNameExtensionFilter) filter, textField.getText())) {
                            chooser.setFileFilter(filter);
                        }
                    }
                }
            }

            if (chooser.showDialog(textField, browserApproveButtonText) == JFileChooser.APPROVE_OPTION) {
                //File selected = processSelectedFile(chooser.getSelectedFile());
                File selected = chooser.getSelectedFile();

                String path = selected.getPath();
                FileFilter filter = chooser.getFileFilter();
                if (filter != null && filter instanceof FileNameExtensionFilter) {

                    boolean found = matchesFilter(((FileNameExtensionFilter) chooser.getFileFilter()), path);

                    if (!found) {
                        String[] exts = ((FileNameExtensionFilter) chooser.getFileFilter()).getExtensions();
                        if (exts.length > 0) {
                            path = FilenameUtils.removeExtension(path);
                            path += "." + exts[0];
                        }
                    }

                }
                textField.setText(path);
            }
        }
    });

    return browseButton;
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java

public static File getFilePath(Component parent, JFileChooser fileChooser, String title, String defaultFileName,
        FileFilter filter) {// w  w  w.  j  a  v  a2  s  . c o m
    fileChooser = initFileChooser(fileChooser, filter);
    if (org.apache.commons.lang.StringUtils.isNotBlank(defaultFileName)) {
        fileChooser.setSelectedFile(new File(defaultFileName));
    }
    int returnVal = fileChooser.showDialog(parent, title);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFile();
    } else {
        return null;
    }
}

From source file:Main.java

/**
 * Displays a {@link JFileChooser} to select a file.
 *
 * @param title The title of the dialog.
 * @param startDirectory The directory where the dialog is initialed opened.
 * @param fileExtension File extension to filter each content of the opened
 * directories. Example ".xml".//from  w  ww.j av a  2s . com
 * @param startFile The preselected file where the dialog is initialed opened.
 * @return The {@link File} object selected, returns null if no file was selected.
 */
public static File chooseFile(String title, String startDirectory, final String fileExtension,
        String startFile) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle(title);

    if (fileExtension != null && !fileExtension.trim().equals("")) {
        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() || pathname.getName().endsWith(fileExtension);
            }

            @Override
            public String getDescription() {
                return "(" + fileExtension + ")";
            }
        };

        chooser.setFileFilter(filter);
    }

    if (startDirectory != null && !startDirectory.trim().equals("")) {
        chooser.setCurrentDirectory(new File(startDirectory));
    }

    if (startFile != null && !startFile.trim().equals("")) {
        chooser.setSelectedFile(new File(startFile));
    }

    int status = chooser.showOpenDialog(null);

    if (status == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    }

    return null;
}

From source file:SaveImage.java

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    if (cb.getActionCommand().equals("SetFilter")) {
        setOpIndex(cb.getSelectedIndex());
        repaint();/*from  ww  w  . j  a  va 2 s. c o  m*/
    } else if (cb.getActionCommand().equals("Formats")) {
        /*
         * Save the filtered image in the selected format. The selected item will
         * be the name of the format to use
         */
        String format = (String) cb.getSelectedItem();
        /*
         * Use the format name to initialise the file suffix. Format names
         * typically correspond to suffixes
         */
        File saveFile = new File("savedimage." + format);
        JFileChooser chooser = new JFileChooser();
        chooser.setSelectedFile(saveFile);
        int rval = chooser.showSaveDialog(cb);
        if (rval == JFileChooser.APPROVE_OPTION) {
            saveFile = chooser.getSelectedFile();
            /*
             * Write the filtered image in the selected format, to the file chosen
             * by the user.
             */
            try {
                ImageIO.write(biFiltered, format, saveFile);
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopExportDisplay.java

private void saveFileAction(String fileName, JFrame frame, ExportDataProvider dataProvider) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setSelectedFile(new File(fileName));
    if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        boolean success = saveFile(dataProvider, selectedFile);
        TopLevelFrame mainFrame = App.getInstance().getMainFrame();
        if (success) {
            mainFrame.showNotification(messages.getMessage(DesktopExportDisplay.class, "export.saveSuccess"),
                    Frame.NotificationType.TRAY);
        } else {//from   w  w  w .j  av a 2 s.  co  m
            mainFrame.showNotification(messages.getMessage(DesktopExportDisplay.class, "export.saveError"),
                    Frame.NotificationType.ERROR);
        }
    }
}

From source file:dylemator.UserList.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    if (this.filenameCombo.getSelectedIndex() == 0)
        return;//from w  w  w . j a va 2 s  .  co  m
    String sheetName = (String) this.filenameCombo.getSelectedItem();
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet(sheetName);
    Row headerRow = sheet.createRow(0);
    String[] headers = exportData.get(0);
    int numOfColumns = headers.length;
    for (int i = 0; i < numOfColumns; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(headers[i]);
    }

    int rowCount = exportData.size();
    for (int rownum = 1; rownum < rowCount; rownum++) {
        Row row = sheet.createRow(rownum);
        String[] values = exportData.get(rownum);
        for (int i = 0; i < numOfColumns; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(values[i]);
        }
    }

    String defaultFilename = "Export.xlsx";
    JFileChooser f = new JFileChooser(System.getProperty("user.dir"));
    f.setSelectedFile(new File(defaultFilename));
    f.setDialogTitle("Wybierz nazw dla pliku eksportu");
    f.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter ff = new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.getName().endsWith(".xlsx"))
                return true;
            return false;
        }

        @Override
        public String getDescription() {
            return "";
        }
    };
    f.setFileFilter(ff);

    File file = null;
    int save = f.showSaveDialog(this);
    if (save == JFileChooser.APPROVE_OPTION)
        file = f.getSelectedFile();
    else
        return;

    FileOutputStream out;
    try {
        out = new FileOutputStream(file);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:calendarexportplugin.exporter.CalExporter.java

/**
 * Shows a file chooser for calendar Files.
 *
 * @return selected File//from   www.  ja  va  2 s  .c o m
 * @param programs
 *          programs that are exported
 */
private File chooseFile(Program[] programs) {
    JFileChooser select = new JFileChooser();

    ExtensionFileFilter vCal = new ExtensionFileFilter(mExtension, mExtensionFilter);
    select.addChoosableFileFilter(vCal);
    String ext = "." + mExtension;

    if (mSavePath != null) {
        select.setSelectedFile(new File(mSavePath));
        select.setFileFilter(vCal);
    }

    // check if all programs have same title. if so, use as filename
    String fileName = programs[0].getTitle();
    for (int i = 1; i < programs.length; i++) {
        if (!programs[i].getTitle().equals(fileName)) {
            fileName = "";
        }
    }

    fileName = CalendarToolbox.cleanFilename(fileName);

    if (StringUtils.isNotEmpty(fileName)) {
        if (mSavePath == null) {
            mSavePath = "";
        }
        select.setSelectedFile(new File((new File(mSavePath).getParent()) + File.separator + fileName + ext));
    }

    if (select.showSaveDialog(
            CalendarExportPlugin.getInstance().getBestParentFrame()) == JFileChooser.APPROVE_OPTION) {

        String filename = select.getSelectedFile().getAbsolutePath();

        if (!filename.toLowerCase().endsWith(ext)) {
            if (filename.endsWith(".")) {
                filename = filename.substring(0, filename.length() - 1);
            }
            filename = filename + ext;
        }

        return new File(filename);
    }

    return null;
}

From source file:grafix.telas.TelaComparativos.java

private void salvarJPEG() {
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {// w w w . j  a  v a 2 s  .c  o  m
            ChartUtilities.saveChartAsJPEG(file, chartPanel.getChart(), chartPanel.getWidth(),
                    chartPanel.getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:jmap2gml.ScriptGui.java

/**
 * Formats the window, initializes the JMap2Script object, and sets up all
 * the necessary events./*  www.  jav  a  2  s .c  o  m*/
 */
public ScriptGui() {
    setTitle("jmap to gml script converter");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().setLayout(new GridBagLayout());

    this.addWindowListener(new WindowListener() {
        @Override
        public void windowOpened(WindowEvent we) {
        }

        @Override
        public void windowClosing(WindowEvent we) {
            saveConfig();
        }

        @Override
        public void windowClosed(WindowEvent we) {
        }

        @Override
        public void windowIconified(WindowEvent we) {
        }

        @Override
        public void windowDeiconified(WindowEvent we) {
        }

        @Override
        public void windowActivated(WindowEvent we) {
        }

        @Override
        public void windowDeactivated(WindowEvent we) {
        }
    });

    GridBagConstraints c = new GridBagConstraints();

    setResizable(true);
    setIconImage((new ImageIcon("spikeup.png")).getImage());

    jta = new JTextArea(38, 30);

    loadConfig();

    JScrollPane jsp = new JScrollPane(jta);
    jsp.setRowHeaderView(new TextLineNumber(jta));
    jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    jsp.setSize(jsp.getWidth(), 608);

    // menu bar
    JMenuBar menubar = new JMenuBar();

    // file menu
    JMenu file = new JMenu("File");

    // load button
    JMenuItem load = new JMenuItem("Load jmap");
    load.addActionListener(ae -> {
        JFileChooser fileChooser = new JFileChooser(prevDirectory);
        fileChooser.setFileFilter(new FileNameExtensionFilter("jmap file", "jmap", "jmap"));

        int returnValue = fileChooser.showOpenDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();

            prevDirectory = selectedFile.getAbsolutePath();

            jm2s = new ScriptFromJmap(selectedFile.getPath(), false);

            jta.setText("");
            jta.append(jm2s.toString());
            jta.setCaretPosition(0);

            writeFile.setEnabled(true);

            drawPanel.setItems(jta.getText().split("\n"));
        }
    });

    // add load to file menu
    file.add(load);

    // button to save script to file
    writeFile = new JMenuItem("Write file");
    writeFile.addActionListener(ae -> {
        if (jm2s != null) {
            PrintWriter out;
            try {
                File f = new File(
                        jm2s.getFileName().substring(0, jm2s.getFileName().lastIndexOf(".jmap")) + ".gml");
                out = new PrintWriter(f);
                out.append(jm2s.toString());
                out.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScriptGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    writeFile.setEnabled(false);

    JMenuItem gmx = new JMenuItem("Export as gmx");
    gmx.addActionListener(ae -> {
        String fn = String.format("%s.room.gmx", prevDirectory);

        JFileChooser fc = new JFileChooser(prevDirectory);
        fc.setSelectedFile(new File(fn));
        fc.setFileFilter(new FileNameExtensionFilter("Game Maker XML", "gmx", "gmx"));
        fc.showDialog(null, "Save");
        File f = fc.getSelectedFile();

        if (f != null) {
            try {
                GMX.itemsToGMX(drawPanel.items, new FileOutputStream(f));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScriptGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    // add to file menu
    file.add(writeFile);
    file.add(gmx);

    // add file menu to the menubar
    menubar.add(file);

    // Edit menu

    // display menu
    JMenu display = new JMenu("Display");

    JMenuItem update = new JMenuItem("Update");

    update.addActionListener(ae -> {
        drawPanel.setItems(jta.getText().split("\n"));
    });

    display.add(update);

    JMenuItem gridToggle = new JMenuItem("Toggle Grid");
    gridToggle.addActionListener(ae -> {
        drawPanel.toggleGrid();
    });
    display.add(gridToggle);

    JMenuItem gridOptions = new JMenuItem("Modify Grid");
    gridOptions.addActionListener(ae -> {
        drawPanel.modifyGrid();
    });
    display.add(gridOptions);

    menubar.add(display);

    // sets the menubar
    setJMenuBar(menubar);

    // add the text area to the window
    c.gridx = 0;
    c.gridy = 0;
    add(jsp, c);

    // initialize the preview panel
    drawPanel = new Preview(this);
    JScrollPane scrollPane = new JScrollPane(drawPanel);

    // add preview panel to the window
    c.gridx = 1;
    c.gridwidth = 2;
    add(scrollPane, c);

    pack();
    setMinimumSize(this.getSize());
    setLocationRelativeTo(null);
    setVisible(true);
    drawPanel.setItems(jta.getText().split("\n"));
}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private File selectOutputDirectory(Component parent, String directoryPath, boolean saveLastSelectionPath,
        SettingsRepository settingsRepository) {
    String targetPath = null;//from   w  ww. j a  v  a2s .  c  o m
    Path savedPath = null;
    if (StringUtils.isNotBlank(directoryPath)) {
        savedPath = Paths.get(directoryPath);
        Path selectionPath = savedPath.getParent();
        if (selectionPath != null) {
            targetPath = selectionPath.toString();
        }
    }
    JFileChooser fileChooser = new JFileChooser(targetPath);
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
    fileChooser.setSelectedFile(savedPath != null ? savedPath.toFile() : null);
    fileChooser.setDialogTitle(getMessage("session.record.save.target"));

    return GuiUtils.openFileSelectionDialog(parent, saveLastSelectionPath, fileChooser, LAST_OUTPUT_PATH,
            settingsRepository);
}