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:it.unibas.spicygui.controllo.file.ActionSaveAsMappingTask.java

@Override
public void performAction() {
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    JFileChooser chooser = vista.getFileChooserSalvaXmlXsd();
    continua = true;/*from ww w .j a  va2s .  co m*/
    File file;
    while (continua) {
        int returnVal = chooser.showSaveDialog(WindowManager.getDefault().getMainWindow());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                file = chooser.getSelectedFile();
                if (!file.exists()) {
                    daoMappingTask.saveMappingTask(mappingTask, file.getAbsolutePath());
                    mappingTask.setModified(false);
                    mappingTask.setToBeSaved(false);
                    continua = false;
                    esito = true;
                } else {
                    chiediConferma(file, mappingTask);
                }
            } catch (DAOException ex) {
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.SAVE_ERROR) + " : " + ex.getMessage(),
                        DialogDescriptor.ERROR_MESSAGE));
                logger.error(ex);
                continua = false;
                esito = false;
            }
        } else {
            continua = false;
            esito = false;
        }
    }
}

From source file:com.intuit.tank.proxy.settings.ui.ProxyConfigDialog.java

protected void openConfig() {
    JFileChooser fileChooser = new JFileChooser();
    File file = new File(".");
    fileChooser.setCurrentDirectory(file);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setFileFilter(new XmlFileFilter());
    int showOpenDialog = fileChooser.showOpenDialog(this);

    if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
        configHandler.setConfigFile(fileChooser.getSelectedFile().getAbsolutePath());
        getProxyConfigPanel().update();//w w w  .  ja  va  2s . c o m
    }
}

From source file:com.alvermont.javascript.tools.shell.ShellJSConsole.java

public String chooseFile() {
    if (this.cwd == null) {
        final String dir = System.getProperty("user.dir");

        if (dir != null) {
            this.cwd = new File(dir);
        }/*  w  ww . j a  v a2 s  . c o  m*/
    }

    if (this.cwd != null) {
        this.dlg.setCurrentDirectory(this.cwd);
    }

    this.dlg.setDialogTitle("Select a file to load");

    final int returnVal = this.dlg.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        final String result = this.dlg.getSelectedFile().getPath();
        this.cwd = new File(this.dlg.getSelectedFile().getParent());

        return result;
    }

    return null;
}

From source file:de.fhbingen.wbs.wpOverview.tabs.APCalendarPanel.java

/**
 * Initialize the work package calendar panel inclusive the listeners.
 *///  ww w  . j  a  v a  2  s  .  c om
private void init() {
    List<Workpackage> userWp = new ArrayList<Workpackage>(WpManager.getUserWp(WPOverview.getUser()));

    Collections.sort(userWp, new APLevelComparator());

    dataset = createDataset(userWp);
    chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);

    final JPopupMenu popup = new JPopupMenu();
    JMenuItem miSave = new JMenuItem(LocalizedStrings.getButton().save(LocalizedStrings.getWbs().timeLine()));
    miSave.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent arg0) {

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new ExtensionAndFolderFilter("jpg", "jpeg")); //NON-NLS
            chooser.setSelectedFile(new File("chart-" //NON-NLS
                    + System.currentTimeMillis() + ".jpg"));
            int returnVal = chooser.showSaveDialog(reference);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    File outfile = chooser.getSelectedFile();
                    ChartUtilities.saveChartAsJPEG(outfile, chart, chartPanel.getWidth(),
                            chartPanel.getWidth());
                    Controller.showMessage(
                            LocalizedStrings.getMessages().timeLineSaved(outfile.getCanonicalPath()));
                } catch (IOException e) {
                    Controller.showError(LocalizedStrings.getErrorMessages().timeLineExportError());
                }
            }
        }

    });
    popup.add(miSave);

    chartPanel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    });
    chartPanel.setMinimumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawWidth(9999);
    chartPanel.setPreferredSize(
            new Dimension((int) chartPanel.getPreferredSize().getWidth(), 50 + 15 * userWp.size()));

    chartPanel.setPopupMenu(null);

    this.setLayout(new BorderLayout());

    this.removeAll();

    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    panel.add(chartPanel, constraints);

    panel.setBackground(Color.white);
    this.add(panel, BorderLayout.CENTER);

    GanttRenderer.setDefaultShadowsVisible(false);
    GanttRenderer.setDefaultBarPainter(new BarPainter() {

        @Override
        public void paintBar(final Graphics2D g, final BarRenderer arg1, final int row, final int col,
                final RectangularShape rect, final RectangleEdge arg5) {

            String wpName = (String) dataset.getColumnKey(col);
            int i = 0;
            int spaceCount = 0;
            while (wpName.charAt(i++) == ' ' && spaceCount < 17) {
                spaceCount++;
            }

            g.setColor(new Color(spaceCount * 15, spaceCount * 15, spaceCount * 15));
            g.fill(rect);
            g.setColor(Color.black);
            g.setStroke(new BasicStroke());
            g.draw(rect);
        }

        @Override
        public void paintBarShadow(final Graphics2D arg0, final BarRenderer arg1, final int arg2,
                final int arg3, final RectangularShape arg4, final RectangleEdge arg5, final boolean arg6) {

        }

    });

    ((CategoryPlot) chart.getPlot()).setRenderer(new GanttRenderer() {
        private static final long serialVersionUID = -6078915091070733812L;

        public void drawItem(final Graphics2D g2, final CategoryItemRendererState state,
                final Rectangle2D dataArea, final CategoryPlot plot, final CategoryAxis domainAxis,
                final ValueAxis rangeAxis, final CategoryDataset dataset, final int row, final int column,
                final int pass) {
            super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass);
        }
    });

}

From source file:SwingFileChooserDemo.java

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(SwingFileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {//from  w w  w.jav a2 s .c o m
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

        //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(SwingFileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

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.  ja va  2  s . c o  m*/
            mainFrame.showNotification(messages.getMessage(DesktopExportDisplay.class, "export.saveError"),
                    Frame.NotificationType.ERROR);
        }
    }
}

From source file:com.adito.upgrade.GUIUpgrader.java

public GUIUpgrader() {
    super(new BorderLayout());
    JPanel info = new JPanel(new BorderLayout(2, 2));

    //        info.setBackground(Color.white);
    //        info.setForeground(Color.black);
    //        info.setOpaque(true);
    info.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    JLabel l = new JLabel("<html><p>This utility upgrades configuration from "
            + "one version 0.1.16 installation to another "
            + "0.2.5+ installation. You may choose which resources you "
            + "wish to be copied. If resources with the same name already " + "exist they will be left as is.");
    l.setIcon(new ImageIcon(GUIUpgrader.class.getResource("upgrader-48x48.png")));
    info.add(l, BorderLayout.CENTER);
    info.add(new JSeparator(JSeparator.HORIZONTAL), BorderLayout.SOUTH);
    mainPanel = new JPanel(new BorderLayout());
    add(info, BorderLayout.NORTH);
    add(mainPanel, BorderLayout.CENTER);

    // Installations panel
    JPanel installations = new JPanel(new GridBagLayout());
    installations.setBorder(BorderFactory.createTitledBorder("Installations"));
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.insets = new Insets(2, 2, 2, 2);
    gbc.weightx = 2.0;/*from   w w w  .  ja va 2 s.  c  o m*/
    UIUtil.jGridBagAdd(installations, new JLabel("Source"), gbc, GridBagConstraints.REMAINDER);
    gbc.weightx = 1.0;
    source = new JTextField();
    source.getDocument().addDocumentListener(this);
    UIUtil.jGridBagAdd(installations, source, gbc, GridBagConstraints.RELATIVE);
    browseSource = new JButton("Browse");
    browseSource.setMnemonic('b');
    browseSource.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser(source.getText());
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setDialogTitle("Select source installation directory (0.16.1)");
            if (chooser.showOpenDialog(GUIUpgrader.this) == JFileChooser.APPROVE_OPTION) {
                source.setText(chooser.getSelectedFile().getAbsolutePath());
            }
        }
    });
    gbc.weightx = 0.0;
    UIUtil.jGridBagAdd(installations, browseSource, gbc, GridBagConstraints.REMAINDER);
    gbc.weightx = 2.0;
    UIUtil.jGridBagAdd(installations, new JLabel("Target"), gbc, GridBagConstraints.REMAINDER);
    gbc.weightx = 1.0;
    target = new JTextField(System.getProperty("user.dir"));
    target.getDocument().addDocumentListener(this);
    UIUtil.jGridBagAdd(installations, target, gbc, GridBagConstraints.RELATIVE);
    browseTarget = new JButton("Browse");
    browseTarget.setMnemonic('r');
    browseTarget.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser(target.getText());
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setDialogTitle("Select target installation directory (0.2.5+)");
            if (chooser.showOpenDialog(GUIUpgrader.this) == JFileChooser.APPROVE_OPTION) {
                target.setText(chooser.getSelectedFile().getAbsolutePath());
            }
        }
    });
    gbc.weightx = 0.0;
    UIUtil.jGridBagAdd(installations, browseTarget, gbc, GridBagConstraints.REMAINDER);
    mainPanel.add(installations, BorderLayout.NORTH);

    // Upgrade selection
    upgradeSelectionPanel = new JPanel();
    upgradeSelectionPanel.setBorder(BorderFactory.createTitledBorder("Upgrades"));
    upgradeSelectionPanel.setLayout(new BoxLayout(upgradeSelectionPanel, BoxLayout.Y_AXIS));
    mainPanel.add(upgradeSelectionPanel, BorderLayout.CENTER);

}

From source file:XMLWriteTest.java

/**
 * Saves the drawing in SVG format, using DOM/XSLT
 *//*from w  w w.  jav a  2s  .  c  o m*/
public void saveDocument() throws TransformerException, IOException {
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Document doc = comp.buildDocument();
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
            "http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd");
    t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 20000802//EN");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(f)));
}

From source file:org.jax.maanova.plot.SaveChartAction.java

/**
 * {@inheritDoc}// w  ww .  ja  v  a 2  s . c  om
 */
public void actionPerformed(ActionEvent e) {
    JFreeChart myChart = this.chart;
    Dimension mySize = this.size;

    if (myChart == null || mySize == null) {
        LOG.severe("Failed to save graph image because of a null value");
        MessageDialogUtilities.errorLater(Maanova.getInstance().getApplicationFrame(),
                "Internal error: Failed to save graph image.", "Image Save Failed");
    } else {
        // use the remembered starting dir
        MaanovaApplicationConfigurationManager configurationManager = MaanovaApplicationConfigurationManager
                .getInstance();
        JMaanovaApplicationState applicationState = configurationManager.getApplicationState();
        FileType rememberedJaxbImageDir = applicationState.getRecentImageExportDirectory();
        File rememberedImageDir = null;
        if (rememberedJaxbImageDir != null && rememberedJaxbImageDir.getFileName() != null) {
            rememberedImageDir = new File(rememberedJaxbImageDir.getFileName());
        }

        // select the image file to save
        JFileChooser fileChooser = new JFileChooser(rememberedImageDir);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setApproveButtonText("Save Graph");
        fileChooser.setDialogTitle("Save Graph as Image");
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.addChoosableFileFilter(PngFileFilter.getInstance());
        fileChooser.setFileFilter(PngFileFilter.getInstance());
        int response = fileChooser.showSaveDialog(Maanova.getInstance().getApplicationFrame());
        if (response == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();

            // tack on the extension if there isn't one
            // already
            if (!PngFileFilter.getInstance().accept(selectedFile)) {
                String newFileName = selectedFile.getName() + "." + PngFileFilter.PNG_EXTENSION;
                selectedFile = new File(selectedFile.getParentFile(), newFileName);
            }

            if (selectedFile.exists()) {
                // ask the user if they're sure they want to overwrite
                String message = "Exporting the graph image to " + selectedFile.getAbsolutePath()
                        + " will overwrite an " + " existing file. Would you like to continue anyway?";
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine(message);
                }

                boolean overwriteOk = MessageDialogUtilities
                        .confirmOverwrite(Maanova.getInstance().getApplicationFrame(), selectedFile);
                if (!overwriteOk) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("overwrite canceled");
                    }
                    return;
                }
            }

            try {
                ChartUtilities.saveChartAsPNG(selectedFile, myChart, mySize.width, mySize.height);

                File parentDir = selectedFile.getParentFile();
                if (parentDir != null) {
                    // update the "recent image directory"
                    ObjectFactory objectFactory = new ObjectFactory();
                    FileType latestJaxbImageDir = objectFactory.createFileType();
                    latestJaxbImageDir.setFileName(parentDir.getAbsolutePath());
                    applicationState.setRecentImageExportDirectory(latestJaxbImageDir);
                }
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "failed to save graph image", ex);
            }
        }
    }
}

From source file:it.unibas.spicygui.controllo.file.ActionSaveMappingTask.java

private void richiediUtilizzoFileChooser(MappingTask mappingTask, File file)
        throws HeadlessException, MissingResourceException {
    JFileChooser chooser = vista.getFileChooserSalvaXmlXsd();
    continua = true;//from  w w w  .j  ava  2  s.  c o m
    while (continua) {
        int returnVal = chooser.showSaveDialog(WindowManager.getDefault().getMainWindow());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                file = chooser.getSelectedFile();
                if (!file.exists()) {
                    daoMappingTask.saveMappingTask(mappingTask, file.getAbsolutePath());
                    mappingTask.setModified(false);
                    mappingTask.setToBeSaved(false);
                    continua = false;
                    esito = true;
                    // modello.putBean(Costanti.ACTUAL_SAVE_FILE, file);
                    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
                    scenario.setSaveFile(file);
                    MappingTaskTopComponent mappingTaskTopComponent = scenario.getMappingTaskTopComponent();
                    mappingTaskTopComponent.initNameTab();
                    enableActions();
                } else {
                    chiediConferma(file, mappingTask);
                }
            } catch (DAOException ex) {
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.SAVE_ERROR) + " : " + ex.getMessage(),
                        DialogDescriptor.ERROR_MESSAGE));
                logger.error(ex);
                continua = false;
                esito = true;
            }
        } else {
            continua = false;
            esito = false;
        }
    }
}