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:com.floreantpos.bo.actions.DataExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    Session session = null;/*  w w w  .j av a  2 s  . c o m*/
    Transaction transaction = null;
    FileWriter fileWriter = null;
    GenericDAO dao = new GenericDAO();

    try {
        JFileChooser fileChooser = getFileChooser();
        int option = fileChooser.showSaveDialog(com.floreantpos.util.POSUtil.getBackOfficeWindow());
        if (option != JFileChooser.APPROVE_OPTION) {
            return;
        }

        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            option = JOptionPane.showConfirmDialog(com.floreantpos.util.POSUtil.getFocusedWindow(),
                    Messages.getString("DataExportAction.1") + file.getName() + "?", //$NON-NLS-1$//$NON-NLS-2$
                    Messages.getString("DataExportAction.3"), //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION);
            if (option != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // fixMenuItemModifierGroups();

        JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter writer = new StringWriter();

        session = dao.createNewSession();
        transaction = session.beginTransaction();

        Elements elements = new Elements();

        //          * 2. USERS
        //          * 3. TAX
        //          * 4. MENU_CATEGORY
        //          * 5. MENU_GROUP
        //          * 6. MENU_MODIFIER
        //          * 7. MENU_MODIFIER_GROUP
        //          * 8. MENU_ITEM
        //          * 9. MENU_ITEM_SHIFT
        //          * 10. RESTAURANT
        //          * 11. USER_TYPE
        //          * 12. USER_PERMISSION
        //          * 13. SHIFT

        elements.setTaxes(TaxDAO.getInstance().findAll(session));
        elements.setMenuCategories(MenuCategoryDAO.getInstance().findAll(session));
        elements.setMenuGroups(MenuGroupDAO.getInstance().findAll(session));
        elements.setMenuModifiers(MenuModifierDAO.getInstance().findAll(session));
        elements.setMenuModifierGroups(MenuModifierGroupDAO.getInstance().findAll(session));
        elements.setMenuItems(MenuItemDAO.getInstance().findAll(session));
        elements.setMenuItemModifierGroups(MenuItemModifierGroupDAO.getInstance().findAll(session));

        //           elements.setUsers(UserDAO.getInstance().findAll(session));
        //           
        //           elements.setMenuItemShifts(MenuItemShiftDAO.getInstance().findAll(session));
        //           elements.setRestaurants(RestaurantDAO.getInstance().findAll(session));
        //           elements.setUserTypes(UserTypeDAO.getInstance().findAll(session));
        //           elements.setUserPermissions(UserPermissionDAO.getInstance().findAll(session));
        //           elements.setShifts(ShiftDAO.getInstance().findAll(session));

        m.marshal(elements, writer);

        transaction.commit();

        fileWriter = new FileWriter(file);
        fileWriter.write(writer.toString());
        fileWriter.close();

        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(),
                Messages.getString("DataExportAction.4")); //$NON-NLS-1$

    } catch (Exception e1) {
        transaction.rollback();
        PosLog.error(getClass(), e1);
        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(), e1.getMessage());
    } finally {
        IOUtils.closeQuietly(fileWriter);
        dao.closeSession(session);
    }
}

From source file:com.stefanbrenner.droplet.ui.actions.OpenFileAction.java

protected void open(final boolean asTemplate) {
    int returnVal = fileChooser.showOpenDialog(getFrame());

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {/*from  www .j  a  va  2 s  .  com*/
            File file = fileChooser.getSelectedFile();

            if (!file.exists()) {
                JOptionPane.showMessageDialog(getFrame(), Messages.getString("SaveFileAction.fileNotFound"), //$NON-NLS-1$
                        Messages.getString("SaveFileAction.fileNotFound"), //$NON-NLS-1$
                        JOptionPane.ERROR_MESSAGE);
                open(false);
                return;
            }

            BufferedReader in = new BufferedReader(new FileReader(file));
            String xml = IOUtils.toString(in);
            in.close();

            JAXBHelper jaxbHelper = new JAXBHelper();
            IDroplet droplet = jaxbHelper.fromXml(xml, IDroplet.class);

            if (asTemplate) {
                // reset droplet
                droplet.reset();
                getDropletContext().setFile(null);
            } else {
                getDropletContext().setFile(file);
            }

            // set droplet to context
            getDropletContext().setDroplet(droplet);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

From source file:com.planetmayo.debrief.satc.util.StraightLineCullingTestForm.java

private void createMenu() {
    JMenu menu = new JMenu("File");
    menu.add(new AbstractAction("Load") {
        private static final long serialVersionUID = 1L;

        @Override/*www.  j  a  v  a  2 s .c o m*/
        public void actionPerformed(ActionEvent e) {
            if (fc.showOpenDialog(StraightLineCullingTestForm.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    loadFile(fc.getSelectedFile());
                } catch (IOException ex) {
                }
            }
        }
    });

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    setJMenuBar(menuBar);
}

From source file:org.vimarsha.ui.DataLoaderForm.java

public DataLoaderForm() {

    for (String str : UIHandler.getInstance().getArchitectureList()) {
        architectureComboBox.addItem(str);
        architectureComboBox.setSelectedItem(null);
    }//from w ww . j  a  v  a  2 s.c  om

    architectureComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            UIHandler.getInstance().setArchitecture((String) architectureComboBox.getSelectedItem());
            trainingModelTextBox.setText(UIHandler.getInstance().getTrainingModel());
        }
    });
    openRAWFileButton.addActionListener(new ActionListener() {
        File file = null;

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            JFileChooser fc = new JFileChooser(".");
            int returnVal = fc.showOpenDialog(Tab0);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
            }
            if ((UIHandler.getInstance().setRawFile(file) == 100)
                    && (UIHandler.getInstance().convertRawToArff() == 100)) {
                saveToARFFFileButton.setEnabled(true);
                attributeList.setListData(UIHandler.getInstance().getArffAttribiutesTableModel().toArray());
                testDataTextField.setText(UIHandler.getInstance().getTestDataName());
            }

        }
    });
    openARFFFileButton.addActionListener(new ActionListener() {
        File file = null;

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            JFileChooser fc = new JFileChooser(".");
            int returnVal = fc.showOpenDialog(Tab0);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
                UIHandler.getInstance().setArffFile(file);
                attributeList.setListData(UIHandler.getInstance().getArffAttribiutesTableModel().toArray());
                saveToARFFFileButton.setEnabled(true);
                testDataTextField.setText(UIHandler.getInstance().getTestDataName());
            }

        }
    });
    saveToARFFFileButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            File file = null;
            JFileChooser fc = new JFileChooser(".");
            int returnVal = fc.showSaveDialog(Tab0);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println(fc.getSelectedFile());
                UIHandler.getInstance().saveAsArff(fc.getSelectedFile());
            }

        }
    });

    attributeList.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent listSelectionEvent) {
            int selectedEvent = attributeList.getSelectedIndex();
            attributesSummaryTable
                    .setModel(UIHandler.getInstance().getArffAttributeInfo(attributeList.getSelectedIndex()));
            DefaultCategoryDataset data = UIHandler.getInstance().getBarChartDataSet(selectedEvent);
            drawBarChart(data);
        }
    });
}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory.//from  ww w.  j a v  a 2 s  .  co m
 *
 *
 * @param owner
 * The frame or dialog that controls the invokation of this dialog.
 * @param defaultDir
 * The directory to show when the dialog opens.
 * @param title
 * Tile for the dialog.
 *
 * @return
 * The selected directory as a File. Null if user cancels dialog without
 * a selection.
 *
 */
public static File getDirectoryChoice(Component owner, File defaultDir, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    JFileChooser chooser = null;
    File choice = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);
    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if ((defaultDir != null) && defaultDir.exists() && defaultDir.isDirectory()) {
        chooser.setCurrentDirectory(defaultDir);
        chooser.setSelectedFile(defaultDir);
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            if (chooser.getSelectedFile().exists()) {
                choice = chooser.getSelectedFile();
            } else {
                File parentFile = new File(chooser.getSelectedFile().getParent());

                choice = parentFile;
            }
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:Result3.java

public void createImage() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("Documents"));
    int retrival = chooser.showSaveDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try {/*from   www .  ja v a2  s .  com*/
            ImageIO.write(bImage1, "png", new File(chooser.getSelectedFile() + ".png"));
        } catch (IOException ex) {
            Logger.getLogger(Result1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:it.unibas.spicygui.controllo.datasource.ActionAddTargetInstanceXml.java

@Override
public void performAction() {
    JFileChooser chooser = vista.getFileChooserApriXML();
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    InstancesTopComponent viewInstancesTopComponent = scenario.getInstancesTopComponent();
    File file;//from  w  w  w.  j a  v  a  2s  .c o  m
    int returnVal = chooser.showDialog(WindowManager.getDefault().getMainWindow(),
            NbBundle.getMessage(Costanti.class, Costanti.LOAD));
    if (returnVal == JFileChooser.APPROVE_OPTION)
        if (scenario.getMappingTask().getSourceProxy().getType().equalsIgnoreCase("XML")) {
            try {
                file = chooser.getSelectedFile();
                DAOXsd daoXsd = new DAOXsd();
                daoXsd.loadInstance(mappingTask.getTargetProxy(), file.getAbsolutePath());
                scenario.addTargetInstance(file.getAbsolutePath());
                if (!viewInstancesTopComponent.isRipulito()) {
                    //viewInstancesTopComponent.clearTarget();
                    viewInstancesTopComponent.createTargetInstanceTree();
                    viewInstancesTopComponent.requestActive();
                    StatusDisplayer.getDefault()
                            .setStatusText(NbBundle.getMessage(Costanti.class, Costanti.ADD_INSTANCE_OK));
                }
            } catch (DAOException ex) {
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.OPEN_ERROR) + " : " + ex.getMessage(),
                        DialogDescriptor.ERROR_MESSAGE));
                logger.error(ex);
            }
        } else {
            DialogDisplayer.getDefault()
                    .notify(new NotifyDescriptor.Message(
                            NbBundle.getMessage(Costanti.class, Costanti.CSV_INST_NOTIF),
                            DialogDescriptor.ERROR_MESSAGE));
        }
}

From source file:it.unibas.spicygui.controllo.datasource.ActionAddSourceInstanceXml.java

@Override
public void performAction() {
    JFileChooser chooser = vista.getFileChooserApriXML();
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    InstancesTopComponent viewInstancesTopComponent = scenario.getInstancesTopComponent();
    File file;//w w w . j  av  a2  s  .  c o m
    int returnVal = chooser.showDialog(WindowManager.getDefault().getMainWindow(),
            NbBundle.getMessage(Costanti.class, Costanti.LOAD));
    if (returnVal == JFileChooser.APPROVE_OPTION)
        if (scenario.getMappingTask().getSourceProxy().getType().equalsIgnoreCase("XML")) {
            try {
                file = chooser.getSelectedFile();
                DAOXsd daoXsd = new DAOXsd();
                daoXsd.loadInstance(mappingTask.getSourceProxy(), file.getAbsolutePath());
                scenario.addSourceInstance(file.getAbsolutePath());
                if (!viewInstancesTopComponent.isRipulito()) {
                    viewInstancesTopComponent.clearSource();
                    viewInstancesTopComponent.createSourceInstanceTree();
                    viewInstancesTopComponent.requestActive();
                    StatusDisplayer.getDefault()
                            .setStatusText(NbBundle.getMessage(Costanti.class, Costanti.ADD_INSTANCE_OK));
                }
            } catch (DAOException ex) {
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.OPEN_ERROR) + " : " + ex.getMessage(),
                        DialogDescriptor.ERROR_MESSAGE));
                logger.error(ex);
            }

        } else {
            DialogDisplayer.getDefault()
                    .notify(new NotifyDescriptor.Message(
                            NbBundle.getMessage(Costanti.class, Costanti.CSV_INST_NOTIF),
                            DialogDescriptor.ERROR_MESSAGE));
        }
}

From source file:edu.smc.mediacommons.panels.SecurityPanel.java

public SecurityPanel() {
    setLayout(null);/*w ww  .j  a  v a2 s  .c om*/

    FILE_CHOOSER = new JFileChooser();

    JButton openFile = Utils.createButton("Open File", 10, 20, 100, 30, null);
    add(openFile);

    JButton saveFile = Utils.createButton("Save File", 110, 20, 100, 30, null);
    add(saveFile);

    JButton decrypt = Utils.createButton("Decrypt", 210, 20, 100, 30, null);
    add(decrypt);

    JButton encrypt = Utils.createButton("Encrypt", 310, 20, 100, 30, null);
    add(encrypt);

    JTextField path = Utils.createTextField(10, 30, 300, 20);
    path.setText("No file selected");

    final JTextArea viewer = new JTextArea();
    JScrollPane pastePane = new JScrollPane(viewer);
    pastePane.setBounds(15, 60, 400, 200);
    add(pastePane);

    openFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (FILE_CHOOSER.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File toRead = FILE_CHOOSER.getSelectedFile();

                if (toRead == null) {
                    JOptionPane.showMessageDialog(getParent(), "The input file does not exist!",
                            "Opening Failed...", JOptionPane.WARNING_MESSAGE);
                } else {
                    try {
                        List<String> lines = IOUtils.readLines(new FileInputStream(toRead), "UTF-8");

                        viewer.setText("");

                        for (String line : lines) {
                            viewer.append(line);
                        }
                    } catch (IOException ex) {

                    }
                }
            }
        }
    });

    saveFile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (FILE_CHOOSER.showSaveDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File toWrite = FILE_CHOOSER.getSelectedFile();

                Utils.writeToFile(viewer.getText(), toWrite);
                JOptionPane.showMessageDialog(getParent(),
                        "The file has now been saved to\n" + toWrite.getPath());
            }
        }
    });

    encrypt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String password = Utils.getPasswordInput(getParent());

            if (password != null) {
                try {
                    BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
                    basicTextEncryptor.setPassword(password);

                    String text = basicTextEncryptor.encrypt(viewer.getText());
                    viewer.setText(text);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(getParent(),
                            "Could not encrypt the text, an unexpected error occurred.", "Encryption Failed...",
                            JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(getParent(),
                        "Could not encrypt the text, as no\npassword has been specified.",
                        "Encryption Failed...", JOptionPane.WARNING_MESSAGE);
            }
        }
    });

    decrypt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String password = Utils.getPasswordInput(getParent());

            if (password != null) {
                try {
                    BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
                    basicTextEncryptor.setPassword(password);

                    String text = basicTextEncryptor.decrypt(viewer.getText());
                    viewer.setText(text);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(getParent(),
                            "Could not decrypt the text, an unexpected error occurred.", "Decryption Failed...",
                            JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(getParent(),
                        "Could not decrypt the text, as no\npassword has been specified.",
                        "Decryption Failed...", JOptionPane.WARNING_MESSAGE);
            }
        }
    });
}

From source file:com.anrisoftware.prefdialog.miscswing.filechoosers.SaveFileDialogModel.java

@Override
public void openDialog(Component parent) throws PropertyVetoException {
    int result = chooser.showSaveDialog(parent);
    if (result == JFileChooser.APPROVE_OPTION) {
        setFileFilter(chooser.getFileFilter());
        setFile(chooser.getSelectedFile());
    } else {//  www  .j a  va2  s.  c  om
        setFileFilter(null);
        setFile(null);
    }
}