Example usage for javax.swing JFileChooser CANCEL_OPTION

List of usage examples for javax.swing JFileChooser CANCEL_OPTION

Introduction

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

Prototype

int CANCEL_OPTION

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

Click Source Link

Document

Return value if cancel is chosen.

Usage

From source file:org.zaproxy.zap.extension.customFire.TechnologyTreePanel.java

/**
 * To save tech settings/*ww w . j av a2s .  com*/
 *  void `
 */
public void saveTechState() {

    //Do Tech ser
    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
    File file = new File(Constant.getZapHome(), "Tech.ser");
    chooser.setSelectedFile(file);

    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".ser")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("customFire.custom.file.format.csp.ser");
        }
    });
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        try {

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(TechnologyTreePanel.this);
            oos.close();
            fos.close();
            View.getSingleton()
                    .showMessageDialog(Constant.messages.getString("customFire.custom.ser.saveTech.success"));

        } catch (IOException e1) {
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("customFire.custom.ser.saveTech.error"));
            return;
        }
    }
    if (rc == JFileChooser.CANCEL_OPTION) {
        chooser.setVisible(false);
        return;
    }

}

From source file:pcgen.gui2.converter.panel.WriteDirectoryPanel.java

@Override
public void setupDisplay(JPanel panel, final CDOMObject pc) {
    panel.setLayout(layout);//w w  w. ja v  a  2s. c  o m
    Component label = new JLabel("Please select the Directory where Converted files should be written: ");
    AbstractButton button = new JButton("Browse...");
    button.setMnemonic('r');
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setDialogType(JFileChooser.OPEN_DIALOG);
            chooser.setCurrentDirectory(path.getParentFile());
            chooser.setSelectedFile(path);
            while (true) {
                int open = chooser.showOpenDialog(null);
                if (open == JFileChooser.APPROVE_OPTION) {
                    File fileToOpen = chooser.getSelectedFile();
                    if (fileToOpen.isDirectory() && fileToOpen.canRead() && fileToOpen.canWrite()) {
                        path = fileToOpen;
                        pc.put(ObjectKey.WRITE_DIRECTORY, path);
                        fileLabel.setText(path.getAbsolutePath());
                        PCGenSettings context = PCGenSettings.getInstance();
                        context.setProperty(PCGenSettings.CONVERT_OUTPUT_SAVE_PATH, path.getAbsolutePath());
                        showWarning();
                        break;
                    }
                    JOptionPane.showMessageDialog(null,
                            "Selection must be a valid " + "(readable & writeable) Directory");
                    chooser.setCurrentDirectory(path.getParentFile());
                } else if (open == JFileChooser.CANCEL_OPTION) {
                    break;
                }
            }
        }
    });
    panel.add(label);
    panel.add(fileLabel);
    panel.add(button);
    panel.add(warningLabel);
    showWarning();
    layout.putConstraint(SpringLayout.NORTH, label, 50, SpringLayout.NORTH, panel);
    layout.putConstraint(SpringLayout.NORTH, fileLabel, 75 + label.getPreferredSize().height,
            SpringLayout.NORTH, panel);
    layout.putConstraint(SpringLayout.NORTH, button, 75 + label.getPreferredSize().height, SpringLayout.NORTH,
            panel);
    layout.putConstraint(SpringLayout.WEST, label, 25, SpringLayout.WEST, panel);
    layout.putConstraint(SpringLayout.WEST, fileLabel, 25, SpringLayout.WEST, panel);
    layout.putConstraint(SpringLayout.EAST, button, -50, SpringLayout.EAST, panel);
    layout.putConstraint(SpringLayout.NORTH, warningLabel, 20, SpringLayout.SOUTH, fileLabel);
    layout.putConstraint(SpringLayout.WEST, warningLabel, 25, SpringLayout.WEST, panel);

    fileLabel.setText(path.getAbsolutePath());
}

From source file:se.cambio.cds.gdl.editor.controller.GDLEditor.java

public void saveCompiledGuideAsObject(byte[] compiledGuide, Guide guide) {
    GDLEditor controller = EditorManager.getActiveGDLEditor();
    String idGuide = controller.getIdGuide();
    if (idGuide == null) {
        idGuide = GDLEditorLanguageManager.getMessage("Guide");
    }//from  ww  w.j ava 2s  . co m
    if (compiledGuide != null) {
        try {
            String guideSource = controller.serializeCurrentGuide();
            if (guideSource != null) {
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        GDLEditorLanguageManager.getMessage("Guide"), new String[] { "guide" });
                fileChooser.setDialogTitle(GDLEditorLanguageManager.getMessage("SaveGuideAsObjectSD"));
                fileChooser.setFileFilter(filter);
                File file = new File(
                        fileChooser.getFileSystemView().getDefaultDirectory() + "/" + idGuide + ".guide");
                fileChooser.setSelectedFile(file);
                int result = fileChooser.showSaveDialog(EditorManager.getActiveEditorWindow());
                File guideFile = fileChooser.getSelectedFile();
                if (result != JFileChooser.CANCEL_OPTION) {
                    idGuide = guideFile.getName();
                    if (idGuide.endsWith(".guide")) {
                        idGuide = idGuide.substring(0, idGuide.length() - 6);
                    }
                    GuideDTO guideDTO = new GuideDTO(idGuide, guideSource, IOUtils.getBytes(guide),
                            compiledGuide, true, Calendar.getInstance().getTime());
                    ObjectOutputStream output = new ObjectOutputStream(
                            new BufferedOutputStream(new FileOutputStream(guideFile)));
                    try {
                        output.writeObject(guideDTO);
                    } catch (Exception e) {
                        ExceptionHandler.handle(e);
                    } finally {
                        output.close();
                    }
                }
            }
        } catch (Exception e) {
            ExceptionHandler.handle(e);
        }
    }
}

From source file:se.cambio.cds.gdl.editor.controller.GDLEditor.java

private void checkGuideArchetypesAndTemplates(Guide guide) throws InternalErrorException {
    if (guide == null || guide.getDefinition() == null
            || guide.getDefinition().getArchetypeBindings() == null) {
        return;/*from w w  w . jav  a 2  s  .  c o m*/
    }
    for (ArchetypeBinding archetypeBinding : guide.getDefinition().getArchetypeBindings()) {
        String archetypeId = archetypeBinding.getArchetypeId();
        String templateId = archetypeBinding.getTemplateId();
        if (templateId == null) {
            if (Archetypes.getArchetypeDTO(archetypeId) == null) {
                int result = ImportUtils.showImportArchetypeDialogAndAddToRepo(
                        EditorManager.getActiveEditorWindow(), new File(archetypeId + ".adl"));
                if (result == JFileChooser.CANCEL_OPTION) {
                    throw new InternalErrorException(
                            new Exception("Archetype '" + archetypeId + "' not found."));
                }
            }
        } else {
            if (Templates.getTemplateDTO(templateId) == null) {
                int result = ImportUtils.showImportTemplateDialog(EditorManager.getActiveEditorWindow(),
                        new File(templateId + ".oet"));
                if (result == JFileChooser.CANCEL_OPTION) {
                    throw new InternalErrorException(new Exception("Template '" + templateId + "' not found."));
                }
            }
        }
    }
}

From source file:se.cambio.cds.util.ExportUtils.java

public static void exportToHTML(Window owner, Guide guide, String lang) {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML", new String[] { "html" });
    fileChooser.setDialogTitle(OpenEHRLanguageManager.getMessage("ExportToHTML"));
    fileChooser.setFileFilter(filter);/* ww  w .jav a  2s.  c  o  m*/
    File selectedFile = new File(guide.getId() + ".html");
    fileChooser.setSelectedFile(selectedFile);
    int result = fileChooser.showSaveDialog(owner);
    if (result != JFileChooser.CANCEL_OPTION) {
        try {
            selectedFile = fileChooser.getSelectedFile();
            FileWriter fstream = new FileWriter(selectedFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(convertToHTML(guide, lang));
            out.close();
        } catch (IOException e) {
            ExceptionHandler.handle(e);
        } catch (InternalErrorException e) {
            ExceptionHandler.handle(e);
        }
    }
}

From source file:ui.FtpDialog.java

private void uploadFileBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadFileBtActionPerformed

    if (connected) {
        JFileChooser uploadFileChooser = new JFileChooser();
        uploadFileChooser.setPreferredSize(new Dimension(650, 450));

        File rootDirectory = new File("C:\\");

        uploadFileChooser//from   w  w  w .  j  a  v a  2s.co m
                .setCurrentDirectory(uploadFileChooser.getFileSystemView().getParentDirectory(rootDirectory));

        uploadFileChooser.setDialogTitle("File to upload");
        int result = uploadFileChooser.showOpenDialog(this);
        switch (result) {

        case JFileChooser.APPROVE_OPTION:
            selectedFile = uploadFileChooser.getSelectedFile();

            Trace.trc("File to upload: " + selectedFile.getName() + " File size: "
                    + FileUtils.byteCountToDisplaySize(selectedFile.length()));

            if (connected) {
                if (!selectedFile.equals(null)) {
                    try {
                        input = new FileInputStream(selectedFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    pb = new ProgressBar();
                    pb.execute();

                    uploadFileChooser.setVisible(false);

                } else {
                    JOptionPane.showMessageDialog(rootFrame, "No file to upload has been chosen!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(rootFrame, "Not connected to a server, cannot upload file!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
            break;

        case JFileChooser.CANCEL_OPTION:
            Trace.trc("Closing file chooser dialog");
            break;

        case JFileChooser.ERROR_OPTION:
            Trace.trc("An error occured");
            break;
        }

    } else {
        JOptionPane.showMessageDialog(rootFrame, "Not connected to a server, cannot upload file!", "Error",
                JOptionPane.ERROR_MESSAGE);
    }

}

From source file:uk.ac.babraham.SeqMonk.Filters.GeneSetFilter.GeneSetDisplay.java

public void actionPerformed(ActionEvent ae) {

    /*   if (ae.getActionCommand().equals("plot")) {
            // ww  w  .  j  ava  2  s  .c o  m
          drawScatterPlot();         
       }
    */
    if (ae.getActionCommand().equals("save_image")) {
        ImageSaver.saveImage(scatterPlotPanel);
    }

    else if (ae.getActionCommand().equals("swap_plot")) {

        if (storesQuantitated()) {

            plotPanel.remove(scatterPlotPanel);

            if (scatterPlotPanel instanceof GeneSetScatterPlotPanel) {
                scatterPlotPanel = new ZScoreScatterPlotPanel(fromStore, toStore, probes,
                        currentSelectedProbeList, dotSizeSlider.getValue(), zScoreLookupTable);
                plotPanel.add(scatterPlotPanel, BorderLayout.CENTER);
                swapPlotButton.setText("Display standard scatterplot");
            } else if (scatterPlotPanel instanceof ZScoreScatterPlotPanel) {
                scatterPlotPanel = new GeneSetScatterPlotPanel(fromStore, toStore, startingProbeList,
                        currentSelectedProbeList, true, dotSizeSlider.getValue(), customRegressionValues,
                        simpleRegression);
                plotPanel.add(scatterPlotPanel, BorderLayout.CENTER);
                swapPlotButton.setText("Display z-score plot");
            }
        }
    }

    else if (ae.getActionCommand().equals("close")) {

        /*   if(currentSelectedProbeList != null){
              currentSelectedProbeList[0].delete();
              //currentSelectedProbeList = null;
                      
           }
        */ this.dispose();

    } else if (ae.getActionCommand().equals("select_all")) {

        if (selectAllButton.isSelected()) {

            for (int i = 0; i < tableModel.selected.length; i++) {

                tableModel.selected[i] = true;

                tableModel.fireTableCellUpdated(i, 0);
            }
            selectAllButton.setText("deselect all");
        } else {

            for (int i = 0; i < tableModel.selected.length; i++) {

                tableModel.selected[i] = false;
                tableModel.fireTableCellUpdated(i, 0);
            }
            selectAllButton.setText("select all");
        }

    }

    else if (ae.getActionCommand().equals("save_selected_probelists")) {

        boolean[] selectedListsBoolean = tableModel.selected;

        if (selectedListsBoolean.length != filterResultsPVals.length) {
            System.err.println("not adding up here");
        }

        else {

            ArrayList<MappedGeneSetTTestValue> selectedListsArrayList = new ArrayList<MappedGeneSetTTestValue>();

            for (int i = 0; i < selectedListsBoolean.length; i++) {

                if (selectedListsBoolean[i] == true) {
                    selectedListsArrayList.add(filterResultsPVals[i]);
                }
            }

            MappedGeneSetTTestValue[] selectedLists = selectedListsArrayList
                    .toArray(new MappedGeneSetTTestValue[0]);

            if (selectedLists.length == 0) {

                JOptionPane.showMessageDialog(SeqMonkApplication.getInstance(), "No probe lists were selected",
                        "No probe lists selected", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            saveProbeLists(selectedLists);

            if (currentSelectedProbeList != null) {
                currentSelectedProbeList[0].delete();
                currentSelectedProbeList = null;
            }
        }
    }

    else if (ae.getActionCommand().equals("save_table")) {
        JFileChooser chooser = new JFileChooser(SeqMonkPreferences.getInstance().getSaveLocation());
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileFilter(new FileFilter() {

            public String getDescription() {
                return "Text files";
            }

            public boolean accept(File f) {
                if (f.isDirectory() || f.getName().toLowerCase().endsWith(".txt")) {
                    return true;
                } else {
                    return false;
                }
            }

        });

        int result = chooser.showSaveDialog(this);
        if (result == JFileChooser.CANCEL_OPTION)
            return;

        File file = chooser.getSelectedFile();
        if (!file.getPath().toLowerCase().endsWith(".txt")) {
            file = new File(file.getPath() + ".txt");
        }

        SeqMonkPreferences.getInstance().setLastUsedSaveLocation(file);

        // Check if we're stepping on anyone's toes...
        if (file.exists()) {
            int answer = JOptionPane.showOptionDialog(this,
                    file.getName() + " exists.  Do you want to overwrite the existing file?", "Overwrite file?",
                    0, JOptionPane.QUESTION_MESSAGE, null, new String[] { "Overwrite and Save", "Cancel" },
                    "Overwrite and Save");

            if (answer > 0) {
                return;
            }
        }

        try {
            PrintWriter p = new PrintWriter(new FileWriter(file));

            TableModel model = table.getModel();

            int rowCount = model.getRowCount();
            int colCount = model.getColumnCount();

            // Do the headers first
            StringBuffer b = new StringBuffer();
            for (int c = 1; c < colCount; c++) {
                b.append(model.getColumnName(c));
                if (c + 1 != colCount) {
                    b.append("\t");
                }
            }

            p.println(b);

            for (int r = 0; r < rowCount; r++) {
                b = new StringBuffer();
                for (int c = 1; c < colCount; c++) {
                    b.append(model.getValueAt(r, c));
                    if (c + 1 != colCount) {
                        b.append("\t");
                    }
                }
                p.println(b);

            }
            p.close();

        }

        catch (FileNotFoundException e) {
            new CrashReporter(e);
        } catch (IOException e) {
            new CrashReporter(e);
        }

    }

    else {
        throw new IllegalArgumentException("Unknown command " + ae.getActionCommand());
    }
}

From source file:view.CertificateManagementDialog.java

private void loadCustomKeystore() {
    JFileChooser jfc = new JFileChooser();
    File path;//from  ww w  . j ava2 s . co m
    if (lastOpened == null) {
        path = new File(System.getProperty("user.home"));
    } else {
        if (lastOpened.exists()) {
            path = lastOpened;
        } else {
            path = new File(System.getProperty("user.home"));
        }
    }
    jfc.setCurrentDirectory(path);
    boolean validKeystore = false;
    while (!validKeystore) {
        int ret = jfc.showOpenDialog(this);
        if (ret == JFileChooser.APPROVE_OPTION) {
            lastOpened = jfc.getSelectedFile();
            KeyStore ks = isValidKeystore(lastOpened, true);
            if (ks != null) {
                validKeystore = true;
                refresh(ks);
            }
        } else if (ret == JFileChooser.CANCEL_OPTION) {
            break;
        }
    }
    if (validKeystore) {
        tfCustomKeystore.setText(lastOpened.getAbsolutePath());
    }
}

From source file:view.MultipleValidationDialog.java

private void writeToFile(String str) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle(Bundle.getBundle().getString("title.saveAs"));
    boolean validPath = false;
    FileNameExtensionFilter pdfFilter = new FileNameExtensionFilter(
            Bundle.getBundle().getString("filter.textFiles") + " (*.txt)", "txt");
    fileChooser.setFileFilter(pdfFilter);
    File preferedFile = new File(Bundle.getBundle().getString("validationReport") + ".txt");
    fileChooser.setSelectedFile(preferedFile);

    while (!validPath) {
        int userSelection = fileChooser.showSaveDialog(this);
        if (userSelection == JFileChooser.CANCEL_OPTION) {
            return;
        }// www.  j  av  a2  s  . c o  m
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            String dest = fileChooser.getSelectedFile().getAbsolutePath();
            if (new File(dest).exists()) {
                String msg = Bundle.getBundle().getString("msg.reportFileNameAlreadyExists");
                Object[] options = { Bundle.getBundle().getString("btn.overwrite"),
                        Bundle.getBundle().getString("btn.chooseNewPath"),
                        Bundle.getBundle().getString("btn.cancel") };
                int opt = JOptionPane.showOptionDialog(null, msg, "", JOptionPane.DEFAULT_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                if (opt == JOptionPane.YES_OPTION) {
                    validPath = true;
                } else if (opt == JOptionPane.CANCEL_OPTION) {
                    return;
                }
            } else {
                validPath = true;
            }

            if (validPath) {
                try (PrintStream out = new PrintStream(new FileOutputStream(dest))) {
                    out.print(str);
                    JOptionPane.showMessageDialog(null,
                            Bundle.getBundle().getString("msg.reportSavedSuccessfully"), "",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (FileNotFoundException ex) {
                    controller.Logger.getLogger().addEntry(ex);
                    JOptionPane.showMessageDialog(null, Bundle.getBundle().getString("msg.reportSaveFailed"),
                            "", JOptionPane.ERROR_MESSAGE);
                }
                break;
            }
        }
    }
}

From source file:view.ViewFiltrar.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

    JFileChooser chooserDiretorio = new JFileChooser(ViewPrincipal.ROOTWOKSPACE);
    chooserDiretorio.setFileFilter(filter);
    chooserDiretorio.setDialogTitle("Escolha o arquivo que deseja importar.");
    resultado = chooserDiretorio.showOpenDialog(getParent());

    if (resultado == JFileChooser.APPROVE_OPTION) {

        File selectedFile = chooserDiretorio.getSelectedFile();
        jTextFieldInputFile.setText(selectedFile.getName());
        String fileNameWithOutExt = FilenameUtils.removeExtension(selectedFile.getName());
        jTextFieldOutputFile//from ww  w . j  av a2  s.c o  m
                .setText(fileNameWithOutExt + "_trimmed." + FilenameUtils.getExtension(selectedFile.getName()));

    } else if (resultado == JFileChooser.CANCEL_OPTION)
        System.out.println("Cancelado.");
}