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.lldp.checksims.ui.results.ScrollViewer.java

/**
 * Create a scroll viewer from a sortable Matrix Viewer
 * @param results the sortableMatrix to view
 * @param toRevalidate frame to revalidate sometimes
 *///  ww  w  . java  2  s.  co  m
public ScrollViewer(SimilarityMatrix exportMatrix, SortableMatrixViewer results, JFrame toRevalidate) {
    resultsView = new JScrollPane(results);
    setBackground(Color.black);
    resultsView.addComponentListener(new ComponentListener() {

        @Override
        public void componentHidden(ComponentEvent arg0) {
        }

        @Override
        public void componentMoved(ComponentEvent arg0) {
        }

        @Override
        public void componentResized(ComponentEvent ce) {
            Dimension size = ce.getComponent().getSize();
            results.padToSize(size);
        }

        @Override
        public void componentShown(ComponentEvent arg0) {
        }
    });

    resultsView.getViewport().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            Rectangle r = resultsView.getViewport().getViewRect();
            results.setViewAt(r);
        }
    });

    resultsView.setBackground(Color.black);
    sidebar = new JPanel();

    setPreferredSize(new Dimension(900, 631));
    setMinimumSize(new Dimension(900, 631));
    sidebar.setPreferredSize(new Dimension(200, 631));
    sidebar.setMaximumSize(new Dimension(200, 3000));
    resultsView.setMinimumSize(new Dimension(700, 631));
    resultsView.setPreferredSize(new Dimension(700, 631));

    sidebar.setBackground(Color.GRAY);

    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

    this.add(sidebar);
    this.add(resultsView);

    resultsView.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    resultsView.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    resultsView.getVerticalScrollBar().setUnitIncrement(16);
    resultsView.getHorizontalScrollBar().setUnitIncrement(16);

    Integer[] presetThresholds = { 80, 60, 40, 20, 0 };
    JComboBox<Integer> threshHold = new JComboBox<Integer>(presetThresholds);
    threshHold.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                Integer item = (Integer) event.getItem();
                results.updateThreshold(item / 100.0);
                toRevalidate.revalidate();
                toRevalidate.repaint();
            }
        }
    });
    threshHold.setSelectedIndex(0);
    results.updateThreshold((Integer) threshHold.getSelectedItem() / 100.0);

    JTextField student1 = new JTextField(15);
    JTextField student2 = new JTextField(15);

    KeyListener search = new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            results.highlightMatching(student1.getText(), student2.getText());
            toRevalidate.revalidate();
            toRevalidate.repaint();
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }
    };

    student1.addKeyListener(search);
    student2.addKeyListener(search);

    Collection<MatrixPrinter> printerNameSet = MatrixPrinterRegistry.getInstance()
            .getSupportedImplementations();
    JComboBox<MatrixPrinter> exportAs = new JComboBox<>(new Vector<>(printerNameSet));
    JButton exportAsSave = new JButton("Save");

    JFileChooser fc = new JFileChooser();

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setCurrentDirectory(new java.io.File("."));
    fc.setDialogTitle("Save results");

    exportAsSave.addActionListener(ae -> {
        MatrixPrinter method = (MatrixPrinter) exportAs.getSelectedItem();

        int err = fc.showDialog(toRevalidate, "Save");
        if (err == JFileChooser.APPROVE_OPTION) {
            try {
                FileUtils.writeStringToFile(fc.getSelectedFile(), method.printMatrix(exportMatrix));
            } catch (InternalAlgorithmError | IOException e1) {
                // TODO log / show error
            }
        }
    });

    JPanel thresholdLabel = new JPanel();
    JPanel studentSearchLabel = new JPanel();
    JPanel fileOutputLabel = new JPanel();

    thresholdLabel.setBorder(BorderFactory.createTitledBorder("Matching Threshold"));
    studentSearchLabel.setBorder(BorderFactory.createTitledBorder("Student Search"));
    fileOutputLabel.setBorder(BorderFactory.createTitledBorder("Save Results"));

    thresholdLabel.add(threshHold);
    studentSearchLabel.add(student1);
    studentSearchLabel.add(student2);
    fileOutputLabel.add(exportAs);
    fileOutputLabel.add(exportAsSave);

    studentSearchLabel.setPreferredSize(new Dimension(200, 100));
    studentSearchLabel.setMinimumSize(new Dimension(200, 100));
    thresholdLabel.setPreferredSize(new Dimension(200, 100));
    thresholdLabel.setMinimumSize(new Dimension(200, 100));
    fileOutputLabel.setPreferredSize(new Dimension(200, 100));
    fileOutputLabel.setMinimumSize(new Dimension(200, 100));

    sidebar.setMaximumSize(new Dimension(200, 4000));

    sidebar.add(thresholdLabel);
    sidebar.add(studentSearchLabel);
    sidebar.add(fileOutputLabel);
}

From source file:ImageProcessingTest.java

/**
 * Open a file and load the image./*from w w  w  .  j a  v  a2  s .co  m*/
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;

    try {
        Image img = ImageIO.read(chooser.getSelectedFile());
        image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, null);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    repaint();
}

From source file:jgraph.JShow.java

/**
 * a driver for this demo// w w  w  . j  a  va  2 s . c o  m
 */
@SuppressWarnings("serial")
public static void showtest(DirectedOrderedSparseMultigraph<Object, Object> graph) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JShow demo = new JShow(graph);

    JMenu menu = new JMenu("Snapshot");
    menu.add(new AbstractAction("To JPEG") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                demo.writeJPEGImage(file);
            }
        }
    });
    menu.add(new AbstractAction("Print") {
        public void actionPerformed(ActionEvent e) {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable(demo);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    });
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    frame.setJMenuBar(menuBar);
    frame.getContentPane().add(demo);
    frame.pack();
    frame.setVisible(true);
}

From source file:it.unibas.spicygui.controllo.provider.composition.MyPopupProviderWidgetChainComposition.java

private void loadDataSource() {
    JFileChooser chooser = vista.getFileChooserApriXSD();
    try {//from w ww.ja  va2  s.co  m
        LayerWidget mainLayer = (LayerWidget) chainWidget.getParentWidget();
        CaratteristicheWidgetChainComposition caratteristicheWidgetChainComposition = (CaratteristicheWidgetChainComposition) mainLayer
                .getChildConstraint(chainWidget);
        ICompositionWidget sourceWidget = caratteristicheWidgetChainComposition.getSourceScenario();
        AbstractCaratteristicheWidgetComposition caratteristicheSourceWidget = (AbstractCaratteristicheWidgetComposition) mainLayer
                .getChildConstraint((Widget) sourceWidget);
        MappingTask mappingTaskSource = caratteristicheSourceWidget.getMutableMappingTask().getMappingTask();
        IDataSourceProxy source = mappingTaskSource.getTargetProxy();
        source.getInstances();
        int returnVal = chooser.showOpenDialog(WindowManager.getDefault().getMainWindow());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            //giannisk
            Scenarios.getNextFreeNumber();

            IDataSourceProxy target = loadXMLDataSource(chooser.getSelectedFile().getAbsolutePath());
            MappingTask mappingTask = new MappingTask(source, target,
                    SpicyEngineConstants.LINES_BASED_MAPPING_TASK);
            caratteristicheWidgetChainComposition.getMutableMappingTask().setMappingTask(mappingTask);
            Scenario scenario = Utility.gestioneScenario(mappingTask, modello, actionProjectTree);
            chainWidget.changeImage(scenario.getImageNumber());
            chainWidget.revalidate();
        }
    } catch (DAOException ex) {
        logger.error(ex);
        DialogDisplayer.getDefault()
                .notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.NEW_ERROR) + " : " + ex.getMessage(),
                        DialogDescriptor.ERROR_MESSAGE));
    } catch (IllegalDataSourceException ex) {
        logger.error(ex);
        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                NbBundle.getMessage(Costanti.class, Costanti.NO_INSTANCES_FOR_COMPOSITION)));

    }
}

From source file:IHM.FenetreAjoutAffiche.java

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

    JFileChooser chooser = new JFileChooser(new File("."));

    chooser.setDialogTitle("ouvrir une image");

    int reponse = chooser.showOpenDialog(this);

    boolean etat;

    if (reponse == JFileChooser.APPROVE_OPTION) {

        InputStream input = null;

        f = chooser.getSelectedFile();//from ww w  . j  av  a 2s  .  c om

        nomAffiche = f.getName();
        nomF = f.getAbsolutePath();

        txtNomPhoto.setText(nomAffiche);

    }

}

From source file:org.nekorp.workflow.desktop.view.FormatoProgramacionView.java

private void importarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importarActionPerformed
    try {//from w  w w . j a v a  2  s .c o m
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Hojas de clculo", "xlsx");
        chooser.setFileFilter(filter);
        String homePath = System.getProperty("user.home");
        File f = new File(new File(homePath).getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showOpenDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            this.application.importarArchivo(chooser.getSelectedFile());
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
    } catch (IOException ex) {
        FormatoProgramacionView.LOGGER.error(ex);
    }
}

From source file:CompareFiles.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:

    String userDir = System.getProperty("user.home");
    JFileChooser folder = new JFileChooser(userDir + "/Desktop");
    folder.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("Excel Files  (*.xls)", "xls");
    folder.setFileFilter(xmlfilter);//from  w  w w  .j a  v  a2 s .  c  om
    //        folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnvalue = folder.showSaveDialog(this);

    File myfolder = null;
    if (returnvalue == JFileChooser.APPROVE_OPTION) {
        myfolder = folder.getSelectedFile();
        //            System.out.println(myfolder);         
    }

    if (myfolder != null) {
        JOptionPane.showMessageDialog(null, "The current choosen file directory is : " + myfolder);
        jLabel1.setText(myfolder.toString());
    }

}

From source file:my.grafos.Maquina.java

static void salvarGrafo() throws FileNotFoundException, IOException {
    /*/*from  w w  w.j av  a 2  s.c  om*/
    FileOutputStream fos = new FileOutputStream("d:\\t.xml");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(Fabrica.listaArestas);
    oos.close();
     */
    final JFileChooser fc = new JFileChooser();
    //Handle save button action.
    int returnVal = fc.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        System.out.println("1 " + fc.getSelectedFile());
        System.out.println("2 " + file);
        //            if (Fabrica.xmlA.length() == 0) {
        if (Fabrica.xmlA.length() == 0) {
            //                System.out.println("No h dados para salvar.");
            return;
        }
        try (OutputStream output = new FileOutputStream(file.getPath())) {
            int count = 0;

            while (count < Fabrica.xmlA.length()) {
                output.write(Fabrica.xmlA.charAt(count));
                count++;
            }
            count = 0;
            while (count < Fabrica.xmlV.length()) {
                output.write(Fabrica.xmlV.charAt(count));
                count++;
            }
        } catch (IOException e) {
        }
    }

}

From source file:lu.lippmann.cdb.ext.hydviga.ui.GapsUIUtil.java

private static void addExportPopupMenu(final Instances ds, final ChartPanel cp) {
    cp.addChartMouseListener(new ChartMouseListener() {
        public void chartMouseClicked(ChartMouseEvent e) {
            final JPopupMenu jPopupMenu = new JPopupMenu("feur");
            final JMenuItem mi1 = new JMenuItem("Export as CSV");
            mi1.addActionListener(new ActionListener() {
                @Override//  ww w  . jav  a 2 s  . co  m
                public void actionPerformed(final ActionEvent e) {
                    final JFileChooser fc = new JFileChooser();
                    fc.setAcceptAllFileFilterUsed(false);
                    final int returnVal = fc.showSaveDialog(cp);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        try {
                            final File file = fc.getSelectedFile();
                            WekaDataAccessUtil.saveInstancesIntoCSVFile(ds, file);
                        } catch (final Exception ee) {
                            ee.printStackTrace();
                        }
                    }
                }
            });
            jPopupMenu.add(mi1);
            jPopupMenu.show(cp, e.getTrigger().getX(), e.getTrigger().getY());
        }

        public void chartMouseMoved(ChartMouseEvent e) {
        }
    });
}

From source file:uk.co.petertribble.jkstat.gui.KstatBaseChartFrame.java

/**
 * Saves the current chart as an image in png format. The user can select
 * the filename, and is asked to confirm the overwrite of an existing file.
 *//*  w  w  w . j a  v  a 2s  .  co  m*/
public void saveImage() {
    JFileChooser fc = new JFileChooser();
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        if (f.exists()) {
            int ok = JOptionPane.showConfirmDialog(this,
                    KstatResources.getString("SAVEAS.OVERWRITE.TEXT") + " " + f.toString(),
                    KstatResources.getString("SAVEAS.CONFIRM.TEXT"), JOptionPane.YES_NO_OPTION);
            if (ok != JOptionPane.YES_OPTION) {
                return;
            }
        }
        BufferedImage bi = kbc.getChart().createBufferedImage(500, 300);
        try {
            ImageIO.write(bi, "png", f);
            /*
             * According to the API docs this should throw an IOException
             * on error, but this doesn't seem to be the case. As a result
             * it's necessary to catch exceptions more generally. Even this
             * doesn't work properly, but at least we manage to convey the
             * message to the user that the write failed, even if the
             * error itself isn't handled.
             */
        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(this, ioe.toString(), KstatResources.getString("SAVEAS.ERROR.TEXT"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}