Example usage for javax.swing JFileChooser getSelectedFile

List of usage examples for javax.swing JFileChooser getSelectedFile

Introduction

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

Prototype

public File getSelectedFile() 

Source Link

Document

Returns the selected file.

Usage

From source file:com.nwn.NwnUpdaterHomeView.java

/**
 * Allow user to specify their NWN directory
 * @param evt //from   ww  w .  j a  v  a 2s  .c o  m
 */
private void btnSelectNwnDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectNwnDirActionPerformed
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new java.io.File("."));
    fc.setDialogTitle("NWN Updater");
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fc.setAcceptAllFileFilterUsed(false);
    int returnVal = fc.showOpenDialog(txtNwnDir);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        txtNwnDir.setText(file.getAbsolutePath());
    }
}

From source file:com.akman.excel.view.frmSelectImage.java

private void btnSelectImageActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSelectImageActionPerformed
{//GEN-HEADEREND:event_btnSelectImageActionPerformed
    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);/*from   www . j  a v a 2  s. c o  m*/

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);
    int res = chooser.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {

        //Saving file inside the file
        File file = chooser.getSelectedFile();

        //        if(!file.equals(filter))
        //        {
        //        JOptionPane.showMessageDialog(null, "Wrong File Selected","ERROR",JOptionPane.ERROR_MESSAGE);
        //        return;
        //        }

        //System.out.println(file.getAbsolutePath());
        ImageIcon image = new ImageIcon(file.getAbsolutePath());

        fileName = file.getAbsolutePath();

        // Get Width And Height of PicLabel
        Rectangle rect = lblImage.getBounds();

        //System.out.println(lblImage.getBounds());
        //Scaling the image to fit in the picLabel
        Image scaledimage = image.getImage().getScaledInstance(rect.width, rect.height, Image.SCALE_DEFAULT);
        //converting the image back to image icon to make an acceptable picLabel
        image = new ImageIcon(scaledimage);

        lblImage.setIcon(image);

        txtPath.setText(fileName);

        try {

            File images = new File(fileName);

            FileInputStream fis = new FileInputStream(images);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }

            person_image = bos.toByteArray();

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

    }
}

From source file:GUI.MyCustomFilter.java

private void NewFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewFileActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        String path = chooser.getSelectedFile().getAbsolutePath();
        String ext = FilenameUtils.getExtension(path);
        outputPath = path;//from www  .  ja v a2s . co  m
        projectSelected = 1;
        //System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
        //System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
        System.out.println("No Selection ");
    }
}

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
 *//*  w  w w. j  a v a2  s.  c o 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:de.fhbingen.wbs.wpOverview.tabs.APCalendarPanel.java

/**
 * Initialize the work package calendar panel inclusive the listeners.
 *//*from  w w  w.  jav a  2s  .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:aurelienribon.gdxsetupui.ui.panels.LibrarySelectionPanel.java

private void browse(String libraryName) {
    File file = libsSelectedFiles.get(libraryName);
    String path = file != null ? file.getPath() : ".";
    JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);

    JFileChooser chooser = new JFileChooser(new File(path));
    chooser.setFileFilter(new FileNameExtensionFilter("Zip files (*.zip)", "zip"));
    chooser.setDialogTitle("Please select the zip archive for \"" + libraryName + "\"");

    if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
        select(libraryName, chooser.getSelectedFile());
    }/*  w w w .j  a va  2s. co m*/
}

From source file:XPathTest.java

/**
     * Open a file and load the document.
     *///from  w  w  w. j a v a  2 s. c om
    public void openFile() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

        chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
            }

            public String getDescription() {
                return "XML files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r != JFileChooser.APPROVE_OPTION)
            return;
        File f = chooser.getSelectedFile();
        try {
            byte[] bytes = new byte[(int) f.length()];
            new FileInputStream(f).read(bytes);
            docText.setText(new String(bytes));
            doc = builder.parse(f);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, e);
        } catch (SAXException e) {
            JOptionPane.showMessageDialog(this, e);
        }
    }

From source file:br.upe.ecomp.dosa.view.wizard.WizardAction.java

@Override
protected void fileBrowseButtonActionPerformed(ActionEvent evt) {
    JFileChooser fileopen = new JFileChooser();
    fileopen.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    int ret = fileopen.showDialog(this, "Open file");

    if (ret == JFileChooser.APPROVE_OPTION) {
        fileLocationTextField.setText(fileopen.getSelectedFile().toString());
    }/*from w w  w.  j  a  v  a 2  s  .  c  om*/
}

From source file:de.quadrillenschule.azocamsyncd.gui.ConfigurationWizardJFrame.java

private void localStorageDirjButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_localStorageDirjButton1ActionPerformed
    boolean success = false;
    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    jfc.setSelectedFile(new File(gp.getProperty(CamSyncProperties.LOCALSTORAGE_PATH)));
    if (jfc.showDialog(jPanel1, "Choose as local directory") == JFileChooser.APPROVE_OPTION) {

        File f = new File(jfc.getSelectedFile().getAbsolutePath(), "azocamsynctest");
        success = f.mkdir();//  ww w  . ja va  2s  .c  o  m
        success = f.delete();
        gp.setProperty(CamSyncProperties.LOCALSTORAGE_PATH, jfc.getSelectedFile().getAbsolutePath());
    }
    if (success) {
        JOptionPane.showMessageDialog(rootPane,
                "You've setup the path for incoming files.\nAll configuration steps are performed now.\n Let's start the service!",
                "Success!", JOptionPane.INFORMATION_MESSAGE);

        step2jCheckBox.setSelected(true);
        step2jCheckBox.setText("Success");
        this.setVisible(false);
    } else {
        JOptionPane.showConfirmDialog(rootPane, "This directory cannot read &write. Please choose another one.",
                "Local storage directory not working", JOptionPane.WARNING_MESSAGE);
    }

}