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:org.parosproxy.paros.control.MenuFileControl.java

public void saveSnapshot() {
    String activeActions = wrapEntriesInLiTags(control.getExtensionLoader().getActiveActions());
    if (!activeActions.isEmpty()) {
        view.showMessageDialog(Constant.messages.getString("menu.file.snapshot.activeactions", activeActions));
        return;/* w ww .j  av a  2  s.  c  o  m*/
    }

    Session session = model.getSession();

    JFileChooser chooser = new JFileChooser(model.getOptionsParam().getUserDirectory());
    // ZAP: set session name as file name proposal
    File fileproposal = new File(session.getSessionName());
    if (session.getFileName() != null && session.getFileName().trim().length() > 0) {
        String proposedFileName;
        // if there is already a file name, use it and add a timestamp
        proposedFileName = StringUtils.removeEnd(session.getFileName(), ".session");
        proposedFileName += "-" + dateFormat.format(new Date()) + ".session";
        fileproposal = new File(proposedFileName);
    }
    chooser.setSelectedFile(fileproposal);
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".session")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("file.format.zap.session");
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(view.getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        model.getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".session")) {
            fileName += ".session";
        }

        try {
            waitMessageDialog = view
                    .getWaitMessageDialog(Constant.messages.getString("menu.file.savingSnapshot")); // ZAP: i18n
            control.snapshotSession(fileName, this);
            log.info("Snapshotting: " + session.getFileName() + " as " + fileName);
            waitMessageDialog.setVisible(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.extension.history.PopupMenuExportResponse.java

private File getOutputFile(HttpMessage msg) {

    String filename = "";
    try {/*from   w  ww .  ja v  a  2  s  . co  m*/
        filename = msg.getRequestHeader().getURI().getPath();
        int pos = filename.lastIndexOf("/");
        filename = filename.substring(pos);
    } catch (Exception e) {
    }
    JFileChooser chooser = new JFileChooser(extension.getModel().getOptionsParam().getUserDirectory());
    if (filename.length() > 0) {
        chooser.setSelectedFile(new File(filename));
    }

    File file = null;
    int rc = chooser.showSaveDialog(extension.getView().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return file;
        }

        extension.getModel().getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());

        return file;

    }
    return file;
}

From source file:org.piraso.ui.base.ExportDialog.java

private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
    File home = new File(System.getProperty("user.home"));
    File pirasoDir = new File(home, "piraso");
    if (!pirasoDir.isDirectory()) {
        pirasoDir.mkdirs();/* ww w .j av a 2 s.  c  o  m*/
    }

    String username = System.getProperty("user.name");

    JFileChooser browserFileChooser = new FileChooserBuilder("piraso-dir")
            .setTitle(NbBundle.getMessage(ExportDialog.class, "ExportDialog.browser.title"))
            .setDefaultWorkingDirectory(pirasoDir).setFileFilter(new PirasoSettingsFileFilter())
            .createFileChooser();

    browserFileChooser.setSelectedFile(new File(pirasoDir, String.format("%s-piraso.settings.prz", username)));
    int result = browserFileChooser.showDialog(this,
            NbBundle.getMessage(ExportDialog.class, "ExportDialog.browser.approveText"));

    if (JFileChooser.APPROVE_OPTION == result) {
        txtTargetFile.setText(browserFileChooser.getSelectedFile().getAbsolutePath());
        refreshButtons();
    }
}

From source file:org.piraso.ui.base.SaveMonitorInstanceDialog.java

private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
    File home = new File(System.getProperty("user.home"));
    File pirasoDir = new File(home, "piraso");
    File pirasoSaveDir = new File(pirasoDir, "saved");
    if (!pirasoSaveDir.isDirectory()) {
        pirasoSaveDir.mkdirs();//from  w  ww  . j  a v a 2s. c o  m
    }

    JFileChooser browserFileChooser = new FileChooserBuilder("piraso-saved-dir")
            .setTitle(NbBundle.getMessage(SaveMonitorInstanceDialog.class,
                    "SaveMonitorInstanceDialog.browser.title"))
            .setFileFilter(new PirasoFileFilter()).setDefaultWorkingDirectory(pirasoSaveDir)
            .createFileChooser();

    String replaceName = StringUtils.replaceChars(name, "[]", "");
    if (!replaceName.endsWith(String.format(".%s", PirasoFileFilter.EXTENSION))) {
        replaceName = String.format("%s.%s", replaceName, PirasoFileFilter.EXTENSION);
    }

    browserFileChooser.setSelectedFile(new File(pirasoSaveDir, replaceName));
    int result = browserFileChooser.showDialog(this, NbBundle.getMessage(SaveMonitorInstanceDialog.class,
            "SaveMonitorInstanceDialog.browser.approveText"));

    if (JFileChooser.APPROVE_OPTION == result) {
        txtTargetFile.setText(browserFileChooser.getSelectedFile().getAbsolutePath());
        refreshButtons();
    }
}

From source file:org.sintef.thingml.FilePanel.java

public FilePanel(final ThingMLPanel editor, final ThingMLFrame frame, File rootF) {
    this.setLayout(new BorderLayout());
    add(new JScrollPane(tree), BorderLayout.CENTER);

    File root = rootF;/*from  w  w w .ja  va 2  s.c  o  m*/
    if (root == null) {
        JFileChooser filechooser = new JFileChooser();
        filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        filechooser.setDialogTitle("Select base directory for ThingML files");

        File dir = ThingMLSettings.getInstance().get_default_work_dir();

        if (dir != null) {
            filechooser.setSelectedFile(dir);
        }

        int returnVal = filechooser.showOpenDialog(null);
        if (filechooser.getSelectedFile() != null && returnVal == JFileChooser.APPROVE_OPTION) {
            ThingMLSettings.getInstance().store_default_work_dir(filechooser.getSelectedFile());
            root = filechooser.getSelectedFile();
        } else {
            System.exit(0);
        }
    }

    FileFilter fileFilter = new FileFilter() {
        @Override
        public boolean accept(File f) {
            return f.getName().endsWith(".thingml");
        }
    };

    final File root2 = root;

    try {
        simpleFileManager = new SimpleFileManager(root, fileFilter);
    } catch (IOException e) {
        e.printStackTrace();
    }
    tree.setModel(new DefaultTreeModel(simpleFileManager.getDirectoryTree()));
    simpleFileManager.startMonitoring();
    FileMonitor fileMonitor = simpleFileManager.getFileMonitor();
    fileMonitor.addClient(this);

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getNewLeadSelectionPath();
            String file = path.getLastPathComponent().toString();
            while (path.getParentPath() != null) {
                path = path.getParentPath();
                file = path.getLastPathComponent() + "/" + file;
            }
            if (file.indexOf("/") > -1) {
                File fileF = new File(root2 + "/" + file.substring(file.indexOf("/")));
                if (fileF.isFile()) {
                    try {
                        final InputStream input = new FileInputStream(fileF.getAbsolutePath());
                        final java.util.List<String> packLines = IOUtils.readLines(input);
                        String content = "";
                        for (String line : packLines) {
                            content += line + "\n";
                        }
                        input.close();
                        editor.loadText(content, fileF);
                        frame.setTitle("ThingML Editor : "
                                + e.getNewLeadSelectionPath().getLastPathComponent().toString());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    });
}

From source file:org.smart.migrate.ui.MigrateMain.java

private void btnExportLogsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportLogsActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File("log.txt"));
    int returnVal = chooser.showSaveDialog(getRootPane());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String filepath = chooser.getSelectedFile().getAbsolutePath();
        filepath = FilenameUtils.removeExtension(filepath) + ".txt";
        try {//from  www.  j  a va 2  s  . c o m
            FileUtils.write(new File(filepath), mmoLogs.getText());
        } catch (IOException ex) {
            Logger.getLogger(MigrateMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:org.squidy.designer.Designer.java

/**
 * Initializes menu bar.//from   ww  w .  j  a  va 2 s .  co m
 */
private void initMenuBar() {

    JMenuBar menuBar = new JMenuBar();

    JMenu workspace = new JMenu("Workspace");
    workspace.add(new AbstractAction("Open from...") {

        /*
         * (non-Javadoc)
         * 
         * @see
         * java.awt.event.ActionListener#actionPerformed(java.awt.event.
         * ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileHidingEnabled(true);
            fileChooser.setFileFilter(new FileFilter() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see
                 * javax.swing.filechooser.FileFilter#accept(java.io.File)
                 */
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".sdy");
                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see javax.swing.filechooser.FileFilter#getDescription()
                 */
                @Override
                public String getDescription() {
                    return "Squidy Workspace";
                }
            });
            int option = fileChooser.showOpenDialog(Designer.this);

            if (option == JFileChooser.APPROVE_OPTION) {

                // Stop replacing workspace if currently running.
                if (data != null) {
                    data.getWorkspace().stop();
                }

                File workspaceFile = fileChooser.getSelectedFile();

                if (storage instanceof LocalJAXBStorage) {
                    ((LocalJAXBStorage) storage).setWorkspaceFile(workspaceFile);
                    load();
                } else {
                    try {
                        data = ModelViewHandler.getModelViewHandler().load(new FileInputStream(workspaceFile));

                        WorkspaceShape workspace = data.getWorkspaceShape();
                        workspace.setModel(data);
                        workspace.setStorageHandler(Designer.this);
                        workspace.initialize();
                        LayoutConstraint lc = workspace.getLayoutConstraint();
                        workspace.setScale(lc.getScale());
                        workspace.setOffset(lc.getX(), lc.getY());

                        getCanvas().getLayer().addChild(workspace);

                        zoomToZoomedShape(data);
                    } catch (SquidyException e1) {
                        e1.printStackTrace();
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    });

    workspace.add(new AbstractAction("Export as...") {

        /*
         * (non-Javadoc)
         * 
         * @see
         * java.awt.event.ActionListener#actionPerformed(java.awt.event.
         * ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileHidingEnabled(true);
            fileChooser.setFileFilter(new FileFilter() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see
                 * javax.swing.filechooser.FileFilter#accept(java.io.File)
                 */
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".sdy");
                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see javax.swing.filechooser.FileFilter#getDescription()
                 */
                @Override
                public String getDescription() {
                    return "Squidy Workspace";
                }
            });

            if (storage instanceof LocalJAXBStorage) {
                fileChooser.setSelectedFile(((LocalJAXBStorage) storage).getWorkspaceFile());
            }

            int option = fileChooser.showSaveDialog(Designer.this);

            if (option == JFileChooser.APPROVE_OPTION) {

                File workspaceFile = fileChooser.getSelectedFile();

                try {
                    ModelViewHandler.getModelViewHandler().save(new FileOutputStream(workspaceFile), data);
                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });

    JMenu options = new JMenu("Options");
    rendering.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            VisualShape.setRenderPrimitiveRect(rendering.isSelected());
            data.setRenderPrimitiveRect(rendering.isSelected());
            storage.store(data);
            repaint();
        }
    });
    options.add(rendering);

    JMenu storage = new JMenu("Storage");

    ButtonGroup group = new ButtonGroup();

    final JRadioButtonMenuItem storageLocalJAXB = new JRadioButtonMenuItem("Local JAXB");
    storageLocalJAXB.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (storageLocalJAXB.isSelected()) {
                setStorageMode(StorageMode.FILE);
            }
        }
    });
    storage.add(storageLocalJAXB);
    group.add(storageLocalJAXB);

    final JRadioButtonMenuItem storageBaseX = new JRadioButtonMenuItem("BaseX");
    storageBaseX.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (storageBaseX.isSelected()) {
                setStorageMode(StorageMode.BASEX);
            }
        }
    });
    storageBaseX.setSelected(storageType.equals(BaseXStorage.class));

    storage.add(storageBaseX);
    group.add(storageBaseX);
    options.add(storage);

    menuBar.add(workspace);
    menuBar.add(options);

    setJMenuBar(menuBar);
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openJFileChooser(int mode, String dialogTitle, boolean open, String filename,
        FileNameExtensionFilter filter) {
    JFileChooser fileChooser;
    // are we forced to open the legacy file chooser?
    if ("true".equals(System.getProperty("tmm.legacy.filechooser"))) {
        fileChooser = new JFileChooser();
    } else {/*from   w  w  w  .  j av a  2 s .co  m*/
        fileChooser = new NativeFileChooser();
    }

    fileChooser.setFileSelectionMode(mode);
    if (lastDir != null) {
        fileChooser.setCurrentDirectory(lastDir.toFile());
    }
    fileChooser.setDialogTitle(dialogTitle);

    int result = -1;
    if (open) {
        result = fileChooser.showOpenDialog(MainWindow.getFrame());
    } else {
        if (StringUtils.isNotBlank(filename)) {
            fileChooser.setSelectedFile(new File(filename));
            fileChooser.setFileFilter(filter);
        }
        result = fileChooser.showSaveDialog(MainWindow.getFrame());
    }

    if (result == JFileChooser.APPROVE_OPTION) {
        if (mode == JFileChooser.DIRECTORIES_ONLY) {
            lastDir = fileChooser.getSelectedFile().toPath();
        } else {
            lastDir = fileChooser.getSelectedFile().getParentFile().toPath();
        }
        return fileChooser.getSelectedFile().toPath();
    }

    return null;
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename./*from  w w  w .  j  av  a 2s  . c  o m*/
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.trzcinka.intellitrac.view.toolwindow.tickets.ticket_editor.BaseTicketEditorForm.java

public BaseTicketEditorForm() {
    ticketsModel.getCurrentTicketModel().addListener(this);
    submitChangesButton.addActionListener(retrieveSubmitButtonActionListener());
    changeHistoryButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor(rootComponent);
            TicketChangesHistoryPopup dialog = new TicketChangesHistoryPopup(window,
                    ticketsModel.getCurrentTicketModel().getCurrentTicket().getChanges());
            dialog.pack();//  w  ww .j  a  va2  s .  co  m
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            dialog.dispose();
        }
    });
    downloadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Attachment attachment = (Attachment) attachmentsList.getSelectedValue();
            OutputStream stream = null;
            if (attachment != null) {
                try {
                    byte[] body = gateway.retrieveAttachment(
                            ticketsModel.getCurrentTicketModel().getCurrentTicket().getId(),
                            attachment.getFileName());
                    JFileChooser fc = new JFileChooser();
                    File dir = fc.getCurrentDirectory();
                    fc.setSelectedFile(new File(dir, attachment.getFileName()));
                    int save = fc.showSaveDialog(rootComponent);

                    if (save == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        stream = new FileOutputStream(file);
                        IOUtils.write(body, stream);
                    }
                } catch (ConnectionFailedException e1) {
                    TracGatewayLocator.handleConnectionProblem();
                } catch (IOException e1) {
                    logger.error("Could not save file", e1);
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
        }
    });
    showDescriptionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Attachment attachment = (Attachment) attachmentsList.getSelectedValue();
            if (attachment != null) {
                JOptionPane popup = new AttachmentDescriptionPopup(attachment.getDescription());
                JDialog dialog = popup.createDialog(null,
                        MessageFormat.format(
                                bundle.getString("tool_window.tickets.ticket_editor.attachments.popup_title"),
                                attachment.getFileName()));
                dialog.setVisible(true);
                dialog.dispose();
            }
        }
    });
    attachmentsList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            Attachment selected = (Attachment) attachmentsList.getSelectedValue();
            if (selected == null) {
                downloadButton.setEnabled(false);
                showDescriptionButton.setEnabled(false);
            } else {
                downloadButton.setEnabled(true);
                if (!(StringUtils.isEmpty(selected.getDescription()))) {
                    showDescriptionButton.setEnabled(true);
                }
            }
        }
    });
    newAttachmentButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor(rootComponent);
            NewAttachmentPopup dialog = new NewAttachmentPopup(window,
                    ticketsModel.getCurrentTicketModel().getCurrentTicket().getId());
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            dialog.dispose();
            synchronizeTicket();
        }
    });
    synchronizeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            synchronizeTicket();
        }
    });
}