Example usage for javax.swing JFileChooser APPROVE_OPTION

List of usage examples for javax.swing JFileChooser APPROVE_OPTION

Introduction

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

Prototype

int APPROVE_OPTION

To view the source code for javax.swing JFileChooser APPROVE_OPTION.

Click Source Link

Document

Return value if approve (yes, ok) is chosen.

Usage

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Persists out the timelord file and allows the user to choose where
 * the file should go.// ww w  . j av a  2 s  . co m
 *
 * @param rwClassName the name of the RW class
 *        (e.g. "net.chaosserver.timelord.data.ExcelDataReaderWriter")
 * @param userSelect allows the user to select where the file should
 *        be persisted.
 */
public void writeTimeTrackData(String rwClassName, boolean userSelect) {
    try {
        Class<?> rwClass = Class.forName(rwClassName);
        TimelordDataReaderWriter timelordDataRW = (TimelordDataReaderWriter) rwClass.newInstance();

        int result = JFileChooser.APPROVE_OPTION;
        File outputFile = timelordDataRW.getDefaultOutputFile();

        if (timelordDataRW instanceof TimelordDataReaderWriterUI) {
            TimelordDataReaderWriterUI timelordDataReaderWriterUI = (TimelordDataReaderWriterUI) timelordDataRW;

            timelordDataReaderWriterUI.setParentFrame(applicationFrame);
            JDialog configDialog = timelordDataReaderWriterUI.getConfigDialog();

            configDialog.pack();
            configDialog.setLocationRelativeTo(applicationFrame);
            configDialog.setVisible(true);
        }

        if (userSelect) {
            if (OsUtil.isMac()) {
                FileDialog fileDialog = new FileDialog(applicationFrame, "Select File", FileDialog.SAVE);

                fileDialog.setDirectory(outputFile.getParent());
                fileDialog.setFile(outputFile.getName());
                fileDialog.setVisible(true);
                if (fileDialog.getFile() != null) {
                    outputFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
                }

            } else {
                JFileChooser fileChooser = new JFileChooser(outputFile.getParentFile());

                fileChooser.setSelectedFile(outputFile);
                fileChooser.setFileFilter(timelordDataRW.getFileFilter());
                result = fileChooser.showSaveDialog(applicationFrame);

                if (result == JFileChooser.APPROVE_OPTION) {
                    outputFile = fileChooser.getSelectedFile();
                }
            }
        }

        if (result == JFileChooser.APPROVE_OPTION) {
            timelordDataRW.writeTimelordData(getTimelordData(), outputFile);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(applicationFrame,
                "Error writing to file.\n" + "Do you have the output file open?", "Save Error",
                JOptionPane.ERROR_MESSAGE, applicationIcon);

        if (log.isErrorEnabled()) {
            log.error("Error persisting file", e);
        }
    }
}

From source file:com.dfki.av.sudplan.vis.wiz.DataSourceSelectionPanel.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    JFileChooser jfc = new JFileChooser();
    jfc.addChoosableFileFilter(new FileNameExtensionFilter("ESRI Shapfile (*.shp)", "shp", "Shp", "SHP"));
    jfc.addChoosableFileFilter(new FileNameExtensionFilter("Zip file (*.zip)", "zip", "ZIP", "Zip"));
    XMLConfiguration xmlConfig = Configuration.getXMLConfiguration();
    String path = xmlConfig.getString("sudplan3D.working.dir");
    File dir;/*from   w  ww . ja va  2  s  .com*/
    if (path != null) {
        dir = new File(path);
        if (dir.exists()) {
            jfc.setCurrentDirectory(dir);
        }
    }
    int retValue = jfc.showOpenDialog(this);

    if (retValue == JFileChooser.APPROVE_OPTION) {
        File f = jfc.getSelectedFile();
        if (f != null) {
            jLabel1.setText(f.getAbsolutePath());
            file = f;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No shp file selected.");
        }
    }
    dir = jfc.getCurrentDirectory();
    path = dir.getAbsolutePath();
    xmlConfig.setProperty("sudplan3D.working.dir", path);
}

From source file:com.mgmtp.jfunk.core.scripting.ScriptContext.java

/**
 * Opens a file chooser dialog which can then be used to choose a file or directory and assign
 * the path of the chosen object to a variable. The name of the variable must be passed as a
 * parameter./* w  w w  . j ava  2  s .  c  om*/
 * 
 * @param fileKey
 *            the key the selected file path is stored under in the configuration
 * @return the chosen file
 */
@Cmd
public File chooseFile(final String fileKey) {
    log.debug("Opening file chooser dialog");
    JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setPreferredSize(new Dimension(600, 326));
    int fileChooserResult = fileChooser.showOpenDialog(null);

    if (fileChooserResult == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        String filename = file.toString();
        log.info("Assigning file path '{}' to property '{}'", filename, fileKey);
        config.put(fileKey, filename);
        return file;
    }

    log.error("No file or directory was chosen, execution will abort");
    throw new IllegalArgumentException("No file or directory was chosen");
}

From source file:com.att.aro.ui.model.diagnostic.GraphPanelHelper.java

public void SaveImageAs(JViewport pane, String graphPanelSaveDirectory) {

    JFileChooser fc = new JFileChooser(graphPanelSaveDirectory);

    // Set up file types
    String[] fileTypesJPG = new String[2];
    String fileDisplayTypeJPG = ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.jpeg");
    fileTypesJPG[0] = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpeg");
    fileTypesJPG[1] = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpg");
    FileFilter filterJPG = new ExtensionFileFilter(fileDisplayTypeJPG, fileTypesJPG);

    fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
    String[] fileTypesPng = new String[1];
    String fileDisplayTypePng = ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.png");
    fileTypesPng[0] = ResourceBundleHelper.getMessageString("fileChooser.contentType.png");
    FileFilter filterPng = new ExtensionFileFilter(fileDisplayTypePng, fileTypesPng);
    fc.addChoosableFileFilter(filterPng);
    fc.setFileFilter(filterJPG);//from w w  w.j  a v  a  2s .c  om
    File plotImageFile = null;

    boolean bSavedOrCancelled = false;
    while (!bSavedOrCancelled) {
        if (fc.showSaveDialog(pane) == JFileChooser.APPROVE_OPTION) {
            String strFile = fc.getSelectedFile().toString();
            String strFileLowerCase = strFile.toLowerCase();
            String fileDesc = fc.getFileFilter().getDescription();
            String fileType = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpg");
            if ((fileDesc.equalsIgnoreCase(
                    ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.png"))
                    || strFileLowerCase.endsWith(ResourceBundleHelper.getMessageString("fileType.filters.dot")
                            + fileTypesPng[0].toLowerCase()))) {
                fileType = fileTypesPng[0];
            }
            if (strFile.length() > 0) {
                // Save current directory
                graphPanelSaveDirectory = fc.getCurrentDirectory().getPath();

                if ((fileType != null) && (fileType.length() > 0)) {
                    String fileTypeLowerCaseWithDot = ResourceBundleHelper
                            .getMessageString("fileType.filters.dot") + fileType.toLowerCase();
                    if (!strFileLowerCase.endsWith(fileTypeLowerCaseWithDot)) {
                        strFile += ResourceBundleHelper.getMessageString("fileType.filters.dot") + fileType;
                    }
                }
                plotImageFile = new File(strFile);
                boolean bAttemptToWriteToFile = true;
                if (plotImageFile.exists()) {
                    if (MessageDialogFactory.showConfirmDialog(pane,
                            MessageFormat.format(
                                    ResourceBundleHelper.getMessageString("fileChooser.fileExists"),
                                    plotImageFile.getAbsolutePath()),
                            ResourceBundleHelper.getMessageString("fileChooser.confirm"),
                            JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
                        bAttemptToWriteToFile = false;
                    }
                }
                if (bAttemptToWriteToFile) {
                    try {
                        if (fileType != null && fileType.equalsIgnoreCase(fileTypesPng[0])) {
                            BufferedImage bufImage = ImageHelper.createImage(pane.getBounds().width,
                                    pane.getBounds().height);
                            Graphics2D g = bufImage.createGraphics();
                            pane.paint(g);
                            ImageIO.write(bufImage, "png", plotImageFile);
                        } else {
                            BufferedImage bufImage = ImageHelper.createImage(pane.getBounds().width,
                                    pane.getBounds().height);
                            Graphics2D g = bufImage.createGraphics();
                            pane.paint(g);
                            ImageIO.write(bufImage, "jpg", plotImageFile);
                        }
                        bSavedOrCancelled = true;
                    } catch (IOException e) {
                        MessageDialogFactory.showMessageDialog(pane, ResourceBundleHelper
                                .getMessageString("fileChooser.errorWritingToFile" + plotImageFile.toString()));
                    }
                }
            }
        } else {
            bSavedOrCancelled = true;
        }
    }
}

From source file:me.philnate.textmanager.windows.MainWindow.java

/**
 * Initialize the contents of the frame.
 *//*from www  .j  a  va  2  s  . c o  m*/
private void initialize() {
    changeListener = new ChangeListener();

    frame = new JFrame();
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Starter.shutdown();
        }
    });
    frame.setBounds(100, 100, 1197, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new MigLayout("", "[grow]", "[][grow][::16px]"));

    customers = new CustomerComboBox();
    customers.addItemListener(changeListener);

    frame.getContentPane().add(customers, "flowx,cell 0 0,growx");

    jScrollPane = new JScrollPane();
    billLines = new BillingItemTable(frame, true);

    jScrollPane.setViewportView(billLines);
    frame.getContentPane().add(jScrollPane, "cell 0 1,grow");

    // for each file added through drag&drop create a new lineItem
    new FileDrop(jScrollPane, new FileDrop.Listener() {

        @Override
        public void filesDropped(File[] files) {
            for (File file : files) {
                addNewBillingItem(Document.loadAndSave(file));
            }
        }
    });

    monthChooser = new JMonthChooser();
    monthChooser.addPropertyChangeListener(changeListener);
    frame.getContentPane().add(monthChooser, "cell 0 0");

    yearChooser = new JYearChooser();
    yearChooser.addPropertyChangeListener(changeListener);
    frame.getContentPane().add(yearChooser, "cell 0 0");

    JButton btnAddLine = new JButton();
    btnAddLine.setIcon(ImageRegistry.getImage("load.gif"));
    btnAddLine.setToolTipText(getCaption("mw.tooltip.add"));
    btnAddLine.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            addNewBillingItem();
        }
    });

    frame.getContentPane().add(btnAddLine, "cell 0 0");

    JButton btnMassAdd = new JButton();
    btnMassAdd.setIcon(ImageRegistry.getImage("load_all.gif"));
    btnMassAdd.setToolTipText(getCaption("mw.tooltip.massAdd"));
    btnMassAdd.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser file = new DocXFileChooser();
            switch (file.showOpenDialog(frame)) {
            case JFileChooser.APPROVE_OPTION:
                File[] files = file.getSelectedFiles();
                if (null != files) {
                    for (File fl : files) {
                        addNewBillingItem(Document.loadAndSave(fl));
                    }
                }
                break;
            default:
                return;
            }
        }
    });

    frame.getContentPane().add(btnMassAdd, "cell 0 0");

    billNo = new JTextField();
    // enable/disable build button based upon text in billNo
    billNo.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            setButtonStates();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            setButtonStates();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
            setButtonStates();
        }

        private void setButtonStates() {
            boolean notBlank = StringUtils.isNotBlank(billNo.getText());
            build.setEnabled(notBlank);
            view.setEnabled(pdf.find(billNo.getText() + ".pdf").size() == 1);
        }
    });
    frame.getContentPane().add(billNo, "cell 0 0");
    billNo.setColumns(10);

    build = new JButton();
    build.setEnabled(false);// disable build Button until there's some
    // billNo entered
    build.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (runningThread == null) {
                try {
                    // check that billNo isn't empty or already used within
                    // another Bill
                    if (billNo.getText().trim().equals("")) {
                        JOptionPane.showMessageDialog(frame, getCaption("mw.dialog.error.billNoBlank.msg"),
                                getCaption("mw.dialog.error.billNoBlank.title"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    try {
                        bill.setBillNo(billNo.getText()).save();
                    } catch (DuplicateKey e) {
                        // unset the internal value as this is already used
                        bill.setBillNo("");
                        JOptionPane.showMessageDialog(frame,
                                format(getCaption("mw.error.billNoUsed.msg"), billNo.getText()),
                                getCaption("mw.dialog.error.billNoBlank.title"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    PDFCreator pdf = new PDFCreator(bill);
                    pdf.addListener(new ThreadCompleteListener() {

                        @Override
                        public void threadCompleted(NotifyingThread notifyingThread) {
                            build.setToolTipText(getCaption("mw.tooltip.build"));
                            build.setIcon(ImageRegistry.getImage("build.png"));
                            runningThread = null;
                            view.setEnabled(DB.pdf.find(billNo.getText() + ".pdf").size() == 1);
                        }
                    });
                    runningThread = new Thread(pdf);
                    runningThread.start();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                build.setToolTipText(getCaption("mw.tooltip.build.cancel"));
                build.setIcon(ImageRegistry.getImage("cancel.gif"));
            } else {
                runningThread.interrupt();
                runningThread = null;
                build.setToolTipText(getCaption("mw.tooltip.build"));
                build.setIcon(ImageRegistry.getImage("build.png"));

            }
        }
    });
    build.setToolTipText(getCaption("mw.tooltip.build"));
    build.setIcon(ImageRegistry.getImage("build.png"));
    frame.getContentPane().add(build, "cell 0 0");

    view = new JButton();
    view.setToolTipText(getCaption("mw.tooltip.view"));
    view.setIcon(ImageRegistry.getImage("view.gif"));
    view.setEnabled(false);
    view.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            File file = new File(System.getProperty("user.dir"),
                    format("template/%s.tmp.pdf", billNo.getText()));
            try {
                pdf.findOne(billNo.getText() + ".pdf").writeTo(file);
                new ProcessBuilder(Setting.find("pdfViewer").getValue(), file.getAbsolutePath()).start()
                        .waitFor();
                file.delete();
            } catch (IOException | InterruptedException e1) {
                // TODO Auto-generated catch block
                LOG.warn("Error while building PDF", e1);
            }
        }
    });
    frame.getContentPane().add(view, "cell 0 0");

    statusBar = new JPanel();
    statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
    statusBar.setLayout(new BoxLayout(statusBar, BoxLayout.X_AXIS));
    GitRepositoryState state = DB.state;
    JLabel statusLabel = new JLabel(String.format("textManager Version v%s build %s",
            state.getCommitIdDescribe(), state.getBuildTime()));
    statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
    statusBar.add(statusLabel);
    frame.add(statusBar, "cell 0 2,growx");

    JMenuBar menuBar = new JMenuBar();
    frame.setJMenuBar(menuBar);

    JMenu menu = new JMenu(getCaption("mw.menu.edit"));
    JMenuItem itemCust = new JMenuItem(getCaption("mw.menu.edit.customer"));
    itemCust.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            new CustomerWindow(customers);
        }
    });
    menu.add(itemCust);

    JMenuItem itemSetting = new JMenuItem(getCaption("mw.menu.edit.settings"));
    itemSetting.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            new SettingWindow();
        }
    });
    menu.add(itemSetting);

    JMenuItem itemImport = new JMenuItem(getCaption("mw.menu.edit.import"));
    itemImport.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            new ImportWindow(new ImportListener() {

                @Override
                public void entriesImported(List<BillingItem> items) {
                    for (BillingItem item : items) {
                        item.setCustomerId(customers.getSelectedCustomer().getId())
                                .setMonth(monthChooser.getMonth()).setYear(yearChooser.getYear());
                        item.save();
                        billLines.addRow(item);
                    }
                }
            }, frame);
        }
    });
    menu.add(itemImport);

    menuBar.add(menu);

    customers.loadCustomer();
    fillTableModel();
}

From source file:de.pavloff.spark4knime.jsnippet.ui.JarListPanel.java

private void onJarFileAdd() {
    DefaultListModel<String> model = (DefaultListModel<String>) m_addJarList.getModel();
    Set<String> hash = new HashSet<>(Collections.list(model.elements()));
    StringHistory history = StringHistory.getInstance("java_snippet_jar_dirs");
    if (m_jarFileChooser == null) {
        File dir = null;//from   w  ww  . j  av  a2  s  . c om
        for (String h : history.getHistory()) {
            File temp = new File(h);
            if (temp.isDirectory()) {
                dir = temp;
                break;
            }
        }
        m_jarFileChooser = new JFileChooser(dir);
        m_jarFileChooser.setFileFilter(new SimpleFileFilter(".zip", ".jar"));
        m_jarFileChooser.setMultiSelectionEnabled(true);
    }
    int result = m_jarFileChooser.showDialog(m_addJarList, "Select");

    if (result == JFileChooser.APPROVE_OPTION) {
        for (File f : m_jarFileChooser.getSelectedFiles()) {
            String s = f.getAbsolutePath();
            if (hash.add(s)) {
                model.addElement(s);
            }
        }
        history.add(m_jarFileChooser.getCurrentDirectory().getAbsolutePath());
    }
}

From source file:com.stam.batchmove.SelectionFrame.java

private void importFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importFileActionPerformed
    String path = sourceDir.getText();
    if (path == null || path.trim().equals("")) {
        JOptionPane.showMessageDialog(this, "You must first select a source directory", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;/* ww  w  .  j a v  a 2  s .  c  o  m*/
    }

    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setDialogTitle("Choose file to import");
    int retVal = fileChooser.showOpenDialog(this);
    if (retVal == JFileChooser.APPROVE_OPTION) {
        File sourceDir = new File(path);
        File[] sourceDirFilesArr = sourceDir.listFiles();
        List<File> sourceDirFiles = Arrays.asList(sourceDirFilesArr);

        File selection = fileChooser.getSelectedFile();

        List<File> files = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(selection))) {
            for (String line; (line = br.readLine()) != null;) {
                if (line != null && !line.trim().equals("")) {
                    File file = BatchMoveUtils.findFileByName(sourceDirFiles, line);
                    if (file != null) {
                        files.add(file);
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String[] columnNames = { "", "Filename", "Size", "Status" };
        Object[][] data = new Object[files.size()][4];

        int fileNo = 0;
        for (File file : files) {
            data[fileNo][0] = file.exists();
            data[fileNo][1] = file.getAbsolutePath();
            data[fileNo][2] = file.length();
            data[fileNo][3] = file.exists() ? "Found" : "Not found";

            fileNo++;
        }

        BatchMoveUtils.showFilesFrame(data, columnNames, this);
    }
}

From source file:edu.umich.robot.GuiApplication.java

/**
 * <p>//from w ww  .  j  ava  2  s .  c  o  m
 * Firing up this application requires a configuration file. If no
 * configuration file is presented on the command line, this is called to
 * prompt the user to select a configuration file.
 * 
 * <p>
 * Future work should probably include some default instead of doing this.
 * 
 * @return The selected, loaded configuration file.
 */
public static Config promptForConfig(Component parent) {

    System.out.println("CLASSPATH: " + System.getenv("CLASSPATH"));
    System.out.println("DYLD_LIBRARY_PATH: " + System.getenv("DYLD_LIBRARY_PATH"));
    System.out.println("LD_LIBRARY_PATH: " + System.getenv("LD_LIBRARY_PATH"));
    System.out.println("SOAR_HOME: " + System.getenv("SOAR_HOME"));
    System.out.println("java.library.path: " + System.getProperty("java.library.path"));

    JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter filter = new FileNameExtensionFilter("Text Config File", "txt");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    int ret = fc.showOpenDialog(parent);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            return new ConfigFile(fc.getSelectedFile().getAbsolutePath());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
    return null;
}

From source file:edu.ku.brc.ui.ImageDisplay.java

/**
 * /*from ww w.j a v a  2 s  . c o m*/
 */
protected void selectNewImage() {
    String oldURL = this.url;
    synchronized (this) {
        if (chooser == null) {
            //      XXX Need to add a filter for just images
            chooser = new JFileChooser();
        }
    }

    int returnVal = chooser.showOpenDialog(UIRegistry.getTopWindow());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = new File(chooser.getSelectedFile().getAbsolutePath());
        try {
            setImage(ImageIO.read(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = file.getAbsolutePath();
        repaint();
    }

    firePropertyChange("imageURL", oldURL, url);
}

From source file:filesscanner.MainWindow.java

private void scanBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scanBtnActionPerformed
    File f = new File("C:");
    JFileChooser chooser = ShowChooser(f);
    int res = chooser.showDialog(this, " ");

    if (res == JFileChooser.APPROVE_OPTION) {

        File[] files = chooser.getSelectedFiles();

        int key = 0;
        for (File file : files) {
            modelDirectories.add(key++, chooser.getSelectedFile().toString());
        }//from  w w w.  j  av  a  2  s.co m

    }
}