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:edu.ku.brc.specify.tools.LocalizerSearchHelper.java

/**
 * @param baseDir//from  w  w w  .j a v a 2  s  .co m
 * @return
 */
public Vector<Pair<String, String>> findOldL10NKeys(final String[] fileNames) {
    initLucene(true);

    //if (srcCodeFilesDir == null)
    {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (srcCodeFilesDir != null) {
            chooser.setSelectedFile(new File(FilenameUtils.getName(srcCodeFilesDir.getAbsolutePath())));
            chooser.setSelectedFile(new File(srcCodeFilesDir.getParent()));
        }

        if (chooser.showOpenDialog(UIRegistry.getMostRecentWindow()) == JFileChooser.APPROVE_OPTION) {
            srcCodeFilesDir = new File(chooser.getSelectedFile().getAbsolutePath());
        } else {
            return null;
        }
    }

    indexSourceFiles();

    Vector<Pair<String, String>> fullNotFoundList = new Vector<Pair<String, String>>();

    try {
        ConversionLogger convLogger = new ConversionLogger();
        convLogger.initialize("resources", "Resources");

        for (String fileName : fileNames) {
            Vector<Pair<String, String>> notFoundList = new Vector<Pair<String, String>>();

            Vector<String> terms = new Vector<String>();

            String propFileName = baseDir.getAbsolutePath() + "/" + fileName;

            File resFile = new File(propFileName + ".properties");
            if (resFile.exists()) {
                List<?> lines = FileUtils.readLines(resFile);
                for (String line : (List<String>) lines) {
                    if (!line.startsWith("#")) {
                        int inx = line.indexOf("=");
                        if (inx > -1) {
                            String[] toks = StringUtils.split(line, "=");
                            if (toks.length > 1) {
                                terms.add(toks[0]);
                            }
                        }
                    }
                }
            } else {
                System.err.println("Doesn't exist: " + resFile.getAbsolutePath());
            }

            String field = "contents";
            QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer);

            for (String term : terms) {
                Query query;
                try {
                    if (term.equals("AND") || term.equals("OR"))
                        continue;

                    query = parser.parse(term);

                    String subTerm = null;
                    int hits = getTotalHits(query, 10);
                    if (hits == 0) {
                        int inx = term.indexOf('.');
                        if (inx > -1) {
                            subTerm = term.substring(inx + 1);
                            hits = getTotalHits(parser.parse(subTerm), 10);

                            if (hits == 0) {
                                int lastInx = term.lastIndexOf('.');
                                if (lastInx > -1 && lastInx != inx) {
                                    subTerm = term.substring(lastInx + 1);
                                    hits = getTotalHits(parser.parse(subTerm), 10);
                                }
                            }
                        }
                    }

                    if (hits == 0 && !term.endsWith("_desc")) {
                        notFoundList.add(new Pair<String, String>(term, subTerm));

                        log.debug("'" + term + "' was not found "
                                + (subTerm != null ? ("SubTerm[" + subTerm + "]") : ""));
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            String fullName = propFileName + ".html";
            TableWriter tblWriter = convLogger.getWriter(FilenameUtils.getName(fullName), propFileName);
            tblWriter.startTable();
            tblWriter.logHdr("Id", "Full Key", "Sub Key");
            int cnt = 1;
            for (Pair<String, String> pair : notFoundList) {
                tblWriter.log(Integer.toString(cnt++), pair.first,
                        pair.second != null ? pair.second : "&nbsp;");
            }
            tblWriter.endTable();

            fullNotFoundList.addAll(notFoundList);

            if (notFoundList.size() > 0 && resFile.exists()) {
                List<String> lines = (List<String>) FileUtils.readLines(resFile);
                Vector<String> linesCache = new Vector<String>();

                for (Pair<String, String> p : notFoundList) {
                    linesCache.clear();
                    linesCache.addAll(lines);

                    int lineInx = 0;
                    for (String line : linesCache) {
                        if (!line.startsWith("#")) {
                            int inx = line.indexOf("=");
                            if (inx > -1) {
                                String[] toks = StringUtils.split(line, "=");
                                if (toks.length > 1) {
                                    if (toks[0].equals(p.first)) {
                                        lines.remove(lineInx);
                                        break;
                                    }
                                }
                            }
                        }
                        lineInx++;
                    }
                }
                FileUtils.writeLines(resFile, linesCache);
            }

        }
        convLogger.closeAll();

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalizerSearchHelper.class, ex);
        ex.printStackTrace();
    }

    return fullNotFoundList;
}

From source file:com.digitalgeneralists.assurance.ui.components.FilePickerTextField.java

public void actionPerformed(ActionEvent e) {
    if (AssuranceActions.chooseFilePathAction.equals(e.getActionCommand())) {
        this.filePicker.setDialogTitle("Choose " + this.fieldName);

        int returnVal = this.filePicker.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = filePicker.getSelectedFile();
            if (AssuranceActions.chooseFilePathAction.equals(e.getActionCommand())) {
                this.pathTextField.setText(file.getAbsolutePath());
            }/*from www  .j av  a 2  s. c  o  m*/
            file = null;
        } else {
        }
    }
}

From source file:presenter.MainPresenter.java

@Override
public void saveMovementsequenceToFile(ActionEvent e) {
    JFileChooser fc = new JFileChooser();

    if (fc.showSaveDialog((Component) e.getSource()) == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {/*from   w  w w.  j  ava 2 s.co m*/
            FileWriter fw = new FileWriter(file);
            fw.write(this.movSeq.toString());
            fw.flush();
            fw.close();
            this.displayStatus("File was written successfully!");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

From source file:cmsc105_mp2.Panels.java

public void createGraph(Data d, float window, Double threshold) {
    XYSeries data = new XYSeries("data");
    double max = Double.MIN_VALUE;
    for (double num : d.plots) {
        if (max < num)
            max = num;/*from w ww  . j a va 2s .  c om*/
    }
    max += 1;

    ArrayList<XYSeries> xy = new ArrayList();
    ArrayList<Integer> points = new ArrayList();

    for (int j = (int) (window / 2); j < d.plots.length - (window / 2); j++) {
        data.add(j, d.plots[j]);
        //System.out.println(points.size());
        if (d.plots[j] > threshold) {
            points.add(j);
        } else {
            if (points.size() >= window) {
                //System.out.println("MIN!");
                XYSeries series = new XYSeries("trend");
                for (int n : points) {
                    series.add(n, max);
                }
                xy.add(series);
            }
            points = new ArrayList();
        }
    }
    if (points.size() >= window) {
        XYSeries series = new XYSeries("trend");
        for (int n : points) {
            series.add(n, max);
        }
        xy.add(series);
    }
    XYSeriesCollection my_data_series = new XYSeriesCollection();
    my_data_series.addSeries(data);
    for (XYSeries x : xy) {
        my_data_series.addSeries(x);
    }

    XYSeries thresh = new XYSeries("threshold");
    for (int j = 0; j < d.plots.length; j++) {
        thresh.add(j, threshold);
    }
    my_data_series.addSeries(thresh);

    //System.out.println(d.name);
    JFreeChart XYLineChart = ChartFactory.createXYLineChart(d.name, "Position", "Average", my_data_series,
            PlotOrientation.VERTICAL, true, true, false);
    bImage1 = (BufferedImage) XYLineChart.createBufferedImage(690, 337);
    imageIcon = new ImageIcon(bImage1);
    jLabel1.setIcon(imageIcon);
    jLabel1.revalidate();
    jLabel1.repaint();
    jButton1.setText("Save as PNG");
    jButton1.repaint();
    jButton1.revalidate();
    jButton1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("Documents"));
            int retrival = chooser.showSaveDialog(null);
            if (retrival == JFileChooser.APPROVE_OPTION) {
                try {
                    ImageIO.write(bImage1, "png", new File(chooser.getSelectedFile() + ".png"));
                } catch (IOException ex) {
                    System.out.println("Unable to Print!");
                }
            }
        }
    });
}

From source file:grafix.principal.Comandos.java

static public void cmdSalvarJPEG() {
    ControleRegistro.alertaRegistro();//from  w ww .j a va  2s .  co m
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(Controle.getTela());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {
            ChartUtilities.saveChartAsJPEG(file, Controle.getJanelaAtiva().getPanelGraficos().getChart(),
                    Controle.getJanelaAtiva().getWidth(), Controle.getJanelaAtiva().getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:ImageIOTest.java

/**
 * Save the current image in a file//  ww w . j  a va 2 s  . co  m
 * @param formatName the file format
 */
public void saveFile(final String formatName) {
    if (images == null)
        return;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatName);
    ImageWriter writer = iter.next();
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = writer.getOriginatingProvider().getFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));

    int r = chooser.showSaveDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    try {
        ImageOutputStream imageOut = ImageIO.createImageOutputStream(f);
        writer.setOutput(imageOut);

        writer.write(new IIOImage(images[0], null, null));
        for (int i = 1; i < images.length; i++) {
            IIOImage iioImage = new IIOImage(images[i], null, null);
            if (writer.canInsertImage(i))
                writer.writeInsert(i, iioImage, null);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
}

From source file:XMLWriteTest.java

/**
 * Saves the drawing in SVG format, using StAX
 *//*from  w w w.  ja  v a 2s . c o  m*/
public void saveStAX() throws FileNotFoundException, XMLStreamException {
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = factory.createXMLStreamWriter(new FileOutputStream(f));
    comp.writeDocument(writer);
    writer.close();
}

From source file:SwingUtil.java

/**
 * Get a file selection using the FileChooser dialog.
 *
 * @param owner/*from   w  w  w. ja v a 2 s.c  o m*/
 * The parent of this modal dialog.
 * @param defaultSelection
 * The default file selection as a file.
 * @param filter
 * An extension filter
 * @param title
 * The caption for the dialog.
 *
 * @return
 * A selected file or null if no selection is made.
 */
public static File getFileChoice(Component owner, File defaultSelection, FileFilter filter, 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;
    File choice = null;
    JFileChooser chooser = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);

    chooser = new JFileChooser();
    if (defaultSelection.isDirectory()) {
        chooser.setCurrentDirectory(defaultSelection);
    } else {
        chooser.setSelectedFile(defaultSelection);
    }
    chooser.setFileFilter(filter);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            choice = chooser.getSelectedFile();
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:com.streamhub.StreamHubLicenseGenerator.java

private JPanel createActionsRow() {
    JPanel actionsRow = new JPanel(new FlowLayout());
    File baseFolder = new File(DEFAULT_CUSTOMERS_DIRECTORY);
    JButton generate = new JButton("Generate");
    generate.addActionListener(new ActionListener() {
        @Override/*w w w  . j a v a 2s  .c o m*/
        public void actionPerformed(ActionEvent e) {
            for (JPanel row : macAddressPanels) {
                try {
                    String macAddress = ((JTextField) row.getComponent(1)).getText();
                    if (macAddress.length() > 0) {
                        String startDate = ((JTextField) row.getComponent(3)).getText();
                        String expiryDate = ((JTextField) row.getComponent(5)).getText();
                        String edition = ((JComboBox) row.getComponent(6)).getSelectedItem().toString();
                        macAddress = macAddress.replaceAll("-", ":").trim();
                        String name = ((JTextField) row.getComponent(8)).getText().trim();
                        String numUsers = ((JTextField) row.getComponent(10)).getText();
                        String licenseString = startDate + "-" + expiryDate + "-" + numUsers + "-" + macAddress
                                + "-" + edition + ":" + name;
                        String hashInput = licenseString + USELESS_KEY;
                        MessageDigest m = MessageDigest.getInstance("SHA-512");
                        m.update(hashInput.getBytes(), 0, hashInput.length());
                        String hash = "==" + new BigInteger(1, m.digest()).toString(16) + "==";
                        StringBuilder licenseText = new StringBuilder();
                        licenseText.append("--").append(licenseString).append("--");
                        licenseText.append(CRLF);
                        licenseText.append(hash);
                        licenseText.append(CRLF);
                        System.out.println(name + ":");
                        System.out.println();
                        System.out.println(licenseText);

                        File licenseDir = new File(folderChooser.getSelectedFile(), name);
                        if (!licenseDir.isDirectory() && !licenseDir.exists()) {
                            licenseDir.mkdir();
                        }
                        File licenseFile = new File(licenseDir, "license.txt");
                        System.out.println("writing to " + licenseFile.getAbsolutePath());
                        FileUtils.writeStringToFile(licenseFile, licenseText.toString());
                    }
                } catch (Exception exception) {
                    System.out.println("Could not generate license");
                    exception.printStackTrace();
                }
            }
        }
    });
    final JButton chooseFolder = new JButton("Choose Folder");
    final JTextField folderDisplay = new JTextField(baseFolder.getAbsolutePath());
    folderChooser = new JFileChooser(baseFolder);
    folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    folderChooser.setSelectedFile(baseFolder);
    chooseFolder.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == chooseFolder) {
                int returnVal = folderChooser.showOpenDialog(StreamHubLicenseGenerator.this);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File folder = folderChooser.getSelectedFile();
                    folderDisplay.setText(folder.getAbsolutePath());
                }
            }
        }
    });

    actionsRow.add(folderDisplay);
    actionsRow.add(chooseFolder);
    actionsRow.add(generate);
    return actionsRow;
}

From source file:org.cytoscape.dyn.internal.graphMetrics.SaveChartDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == cancelButton) {
        this.setVisible(false);
        this.dispose();
    } else if (e.getSource() == saveChartButton) {
        JFileChooser saveFileDialog = new JFileChooser();
        saveFileDialog// w w w  .j  a  va  2  s  .c  o m
                .addChoosableFileFilter(new ExtensionFileFilter(".jpeg", ".jpg", "Jpeg images (.jpeg, .jpg)"));
        saveFileDialog.addChoosableFileFilter(
                new ExtensionFileFilter(".png", "Portable Network Graphic images (.png)"));
        saveFileDialog
                .addChoosableFileFilter(new ExtensionFileFilter(".svg", "Scalable Vector Graphics (.svg)"));
        int save = saveFileDialog.showSaveDialog(this);
        if (save == JFileChooser.APPROVE_OPTION) {
            File file = saveFileDialog.getSelectedFile();
            int width = ((SpinnerNumberModel) widthSpinner.getModel()).getNumber().intValue();
            int height = ((SpinnerNumberModel) heightSpinner.getModel()).getNumber().intValue();

            ExtensionFileFilter filter = null;
            try {
                filter = (ExtensionFileFilter) saveFileDialog.getFileFilter();
                if (!filter.hasExtension(file)) {
                    file = filter.appendExtension(file);
                }
            } catch (ClassCastException ex) {
                // Try to infer the type of file by its extension
                FileFilter[] filters = saveFileDialog.getChoosableFileFilters();
                for (int i = 0; i < filters.length; ++i) {
                    if (filters[i] instanceof ExtensionFileFilter) {
                        filter = (ExtensionFileFilter) filters[i];
                        if (filter.hasExtension(file)) {
                            break;
                        }
                        filter = null;
                    }
                }

                if (filter == null) {
                    // Could not infer the type
                    JOptionPane.showMessageDialog(null,
                            "File type not specified!\nWhen giving file name, please also select one of the supported file types.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            // Save the chart to the specified file name
            try {
                String ext = filter.getExtension();
                if (ext.equals("jpeg")) {
                    ChartUtilities.saveChartAsJPEG(file, chart, width, height);
                } else if (ext.equals("png")) {
                    ChartUtilities.saveChartAsPNG(file, chart, width, height);
                } else {
                    VectorGraphics graphics = new SVGGraphics2D(file, new Dimension(width, height));
                    graphics.startExport();
                    chart.draw(graphics, new Rectangle2D.Double(0, 0, width, height));
                    graphics.endExport();
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "An error occurred while creating or writing to the file.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            this.setVisible(false);
            this.dispose();
        } else if (save == JFileChooser.ERROR_OPTION) {
            JOptionPane.showMessageDialog(null, "An error occurred while initializing the window.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}