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:es.mityc.firmaJava.libreria.pkcs7.ValidaTarjeta.java

/**
 * This method initializes jExaminarButton1   
 *    /*from www .  java  2 s. c  om*/
 * @return javax.swing.JButton   
 */
private JButton getJExaminarButton1() {
    if (jExaminarButton1 == null) {
        jExaminarButton1 = new JButton();
        jExaminarButton1.setPreferredSize(new Dimension(90, 20));
        jExaminarButton1.setText(I18n.getResource(LIBRERIAXADES_VALIDARTARJETA_TEXTO_10));
        jExaminarButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                final JFileChooser libreria = new JFileChooser();
                libreria.setDialogTitle(I18n.getResource(LIBRERIAXADES_VALIDARTARJETA_TEXTO_11));
                int returnVal = libreria.showOpenDialog(jPanel);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    jNuevaLibreriaTextField.setText(libreria.getSelectedFile().toString());
                }
            }
        });
    }
    return jExaminarButton1;
}

From source file:io.github.jeremgamer.editor.panels.MusicFrame.java

public MusicFrame(JFrame frame, final GeneralSave gs) {

    ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
    try {//  www  .  j a  va  2  s.c o  m
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png")));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    this.setIconImages((List<? extends Image>) icons);

    this.setTitle("Musique");
    this.setSize(new Dimension(300, 225));

    this.addWindowListener(new WindowListener() {
        @Override
        public void windowActivated(WindowEvent event) {
        }

        @Override
        public void windowClosed(WindowEvent event) {
        }

        @Override
        public void windowClosing(WindowEvent event) {
            try {
                gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (clip != null) {
                clip.stop();
                clip.close();
                try {
                    audioStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void windowDeactivated(WindowEvent event) {
        }

        @Override
        public void windowDeiconified(WindowEvent event) {
        }

        @Override
        public void windowIconified(WindowEvent event) {
        }

        @Override
        public void windowOpened(WindowEvent event) {
        }
    });

    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

    this.setModal(true);
    this.setLocationRelativeTo(frame);

    JPanel properties = new JPanel();
    properties.setBorder(BorderFactory.createTitledBorder("Lecture"));
    ButtonGroup bg = new ButtonGroup();
    bg.add(one);
    bg.add(loop);
    one.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            JRadioButton rb = (JRadioButton) event.getSource();
            if (rb.isSelected()) {
                gs.set("music.reading", 0);
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    if (clip.isRunning())
                        clip.loop(0);
                }
            }
        }
    });
    loop.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            JRadioButton rb = (JRadioButton) event.getSource();
            if (rb.isSelected()) {
                gs.set("music.reading", 1);
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    if (clip.isRunning())
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                }
            }
        }
    });
    properties.add(one);
    properties.add(loop);
    if (gs.getInt("music.reading") == 0) {
        one.setSelected(true);
    } else {
        loop.setSelected(true);
    }

    volume.setMaximum(100);
    volume.setMinimum(0);
    volume.setValue(30);
    volume.setPaintTicks(true);
    volume.setPaintLabels(true);
    volume.setMinorTickSpacing(10);
    volume.setMajorTickSpacing(20);
    volume.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent event) {
            JSlider slider = (JSlider) event.getSource();
            double value = slider.getValue();
            gain = value / 100;
            dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
            if (clip != null)
                gainControl.setValue(dB);
            gs.set("music.volume", (int) value);
        }
    });
    volume.setValue(gs.getInt("music.volume"));
    properties.add(volume);
    properties.setPreferredSize(new Dimension(300, 125));

    content.add(properties);

    JPanel browsePanel = new JPanel();
    browsePanel.setBorder(BorderFactory.createTitledBorder(""));
    JButton browse = new JButton("Parcourir...");
    if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
        preview.setEnabled(false);
        browse.setText("");
        try {
            browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    browse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
                if (clip != null) {
                    clip.stop();
                    clip.close();
                    try {
                        audioStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                name.setText("");
                preview.setEnabled(false);
                button.setText("Parcourir...");
                button.setIcon(null);
                new File("projects/" + Editor.getProjectName() + "/music.wav").delete();
                gs.set("music.name", "");
            } else {
                String path = null;
                JFileChooser chooser = new JFileChooser(Editor.lastPath);
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav");
                chooser.setFileFilter(filter);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int option = chooser.showOpenDialog(null);
                if (option == JFileChooser.APPROVE_OPTION) {
                    path = chooser.getSelectedFile().getAbsolutePath();
                    Editor.lastPath = chooser.getSelectedFile().getParent();
                    copyMusic(new File(path));
                    button.setText("");
                    try {
                        button.setIcon(
                                new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    gs.set("music.name", new File(path).getName());
                    try {
                        gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    name.setText(new File(path).getName());
                    preview.setEnabled(true);
                }
            }
        }

    });
    if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
        preview.setEnabled(true);
    } else {
        preview.setEnabled(false);
    }
    preview.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JToggleButton tb = (JToggleButton) event.getSource();
            if (tb.isSelected()) {
                try {
                    audioStream = AudioSystem.getAudioInputStream(
                            new File("projects/" + Editor.getProjectName() + "/music.wav"));
                    format = audioStream.getFormat();
                    info = new DataLine.Info(Clip.class, format);
                    clip = (Clip) AudioSystem.getLine(info);
                    clip.open(audioStream);
                    clip.start();
                    gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                    gainControl.setValue(dB);
                    if (loop.isSelected()) {
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                    } else {
                        clip.loop(0);
                    }
                    clip.addLineListener(new LineListener() {
                        @Override
                        public void update(LineEvent event) {
                            Clip clip = (Clip) event.getSource();
                            if (!clip.isRunning()) {
                                preview.setSelected(false);
                                clip.stop();
                                clip.close();
                                try {
                                    audioStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    });
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            } else {
                clip.stop();
                clip.close();
                try {
                    audioStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    });
    JPanel buttons = new JPanel();
    buttons.setLayout(new BorderLayout());
    buttons.add(browse, BorderLayout.WEST);
    buttons.add(preview, BorderLayout.EAST);
    browsePanel.setLayout(new BorderLayout());
    browsePanel.add(buttons, BorderLayout.NORTH);
    browsePanel.add(name, BorderLayout.SOUTH);

    name.setPreferredSize(new Dimension(280, 25));
    name.setText(gs.getString("music.name"));
    content.add(browsePanel);

    this.setContentPane(content);
    this.setVisible(true);
}

From source file:gui.InboxPanel.java

private void openVerifyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openVerifyButtonActionPerformed
    JFileChooser chooser = new JFileChooser();
    int retrieval = chooser.showOpenDialog(null);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Public file", "pub");
    chooser.setFileFilter(filter);//from w  w  w . j  a v a 2 s .co  m
    if (retrieval == JFileChooser.APPROVE_OPTION) {
        FileInputStream fis = null;
        try {
            File file = chooser.getSelectedFile();
            Path path = Paths.get(file.getAbsolutePath());
            fis = new FileInputStream(file);
            //Construct BufferedReader from InputStreamReader
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            try {
                String x = br.readLine();
                String y = br.readLine();
                publickey = new BigPoint(new BigInteger(x), new BigInteger(y));
                System.out.println("Public key : " + publickey.getX() + publickey.getY());
                br.close();
            } catch (IOException ex) {
                Logger.getLogger(InboxPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(InboxPanel.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(InboxPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:coreferenceresolver.gui.MainGUI.java

private void markupBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_markupBtnActionPerformed
    JFileChooser inputFileChooser = new JFileChooser(defaulPath);
    inputFileChooser.setDialogTitle("Choose where your markup file saved");
    inputFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    if (inputFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        String[] inputFilePath = inputFilePathTF.getText().split("\\\\");
        String inputFileName = inputFilePath[inputFilePath.length - 1];
        markupFilePathTF.setText(inputFileChooser.getSelectedFile().getAbsolutePath() + File.separator
                + inputFileName + ".markup");
        noteTF.setText("Markup waiting ...");
        new Thread(new Runnable() {
            @Override/*w w  w  .  j a  va  2  s .  co m*/
            public void run() {
                try {
                    MarkupMain.markup(inputFilePathTF.getText(), markupFilePathTF.getText());
                    noteTF.setText("Markup done!");
                    String folderPathOpen = markupFilePathTF.getText().substring(0,
                            markupFilePathTF.getText().lastIndexOf(File.separatorChar));
                    Desktop.getDesktop().open(new File(folderPathOpen));
                } catch (IOException ex) {
                    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    } else {
        return;
    }
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public void fileSaveHex(SpinCADBank bank) {
    // Create a file chooser
    String savedPath = prefs.get("MRUHexFolder", "");

    final JFileChooser fc = new JFileChooser(savedPath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Hex Files", "hex");
    fc.setFileFilter(filter);/*from  w w  w . j  a v  a  2  s  .  c o  m*/
    fc.showSaveDialog(new JFrame());
    File fileToBeSaved = fc.getSelectedFile();

    if (!fc.getSelectedFile().getAbsolutePath().endsWith(".hex")) {
        fileToBeSaved = new File(fc.getSelectedFile() + ".hex");
    }
    int n = JOptionPane.YES_OPTION;
    if (fileToBeSaved.exists()) {
        JFrame frame1 = new JFrame();
        n = JOptionPane.showConfirmDialog(frame1, "Would you like to overwrite it?", "File already exists!",
                JOptionPane.YES_NO_OPTION);
    }
    if (n == JOptionPane.YES_OPTION) {
        String filePath;
        try {
            filePath = fileToBeSaved.getPath();
            fileToBeSaved.delete();
        } finally {
        }
        for (int i = 0; i < 8; i++) {
            try {
                if (bank.patch[i].isHexFile) {
                    fileSaveHex(i, bank.patch[i].hexFile, filePath);
                } else {
                    fileSaveHex(i, bank.patch[i].patchModel.getRenderBlock().generateHex(), filePath);
                }
            } catch (IOException e) {
                JOptionPane.showOptionDialog(null, "File save error!", "Error", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, null, null);

                e.printStackTrace();
            }
        }
        saveMRUHexFolder(filePath);
    }
}

From source file:dylemator.DylematorUI.java

private void questionsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_questionsMenuItemActionPerformed
    JFileChooser f = new JFileChooser(System.getProperty("user.dir"));
    int result = f.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION)
        this.file = f.getSelectedFile();
    else//  w  w w  .  j a  v a 2s  .com
        return;

    displayCenteredText("");

    QuestionParser parser = new QuestionParser(file);
    List<Dilemma> dList = parser.getDilemmaList();
    this.warmupList = parser.getWarmupList();
    qd = new QuestionDialog(this, true);
    qd.setDilemmas(dList);
    qd.clearSelectedDilemmas();
    if (parser.isXmlFileOk() == true) {
        qd.setVisible(true);
        qd.clearAll();
        this.startButton.setEnabled(true);
    } else {
        displayCenteredText("Plik jest niepoprawny!");
        return;
    }
    if (ud.getName() == null || ud.getName().isEmpty()) {
        displayCenteredText("Wpisz dane uytkownika");
    } else {
        this.startButton.setText("START");
    }

}

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

private void btnAddFileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAddFileActionPerformed
{//GEN-HEADEREND:event_btnAddFileActionPerformed

    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files", "xlsx", "xlsm", "xlt", "xlsb",
            "xltx", "xltm", "xls", "xlt", "xls");

    chooser.setFileFilter(filter);//  w  w  w .j a  v a2 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) {

        File file = chooser.getSelectedFile();

        // checking file extension. it must be excel file. 
        if (file.equals(filter)) {
            JOptionPane.showMessageDialog(null, "Wrong File selected", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }

        fileName = file.getAbsolutePath();
        txtPath.setText(fileName);

    }

}

From source file:edu.uchc.octane.OctaneWindowControl.java

/**
 * Ask user to choose a file and import drift calibration data from the file 
 *//*from  w w w  . ja v  a  2 s  .co  m*/
public void importDriftData() {

    JFileChooser fc = new JFileChooser();
    if (fc.showOpenDialog(IJ.getApplet()) == JFileChooser.APPROVE_OPTION) {

        try {

            dataset_.importDriftData(fc.getSelectedFile());

        } catch (IOException e) {

            IJ.error("An IO error occured reading file: " + fc.getSelectedFile().getName());
        }
    }
}

From source file:dylemator.UserList.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    if (this.filenameCombo.getSelectedIndex() == 0)
        return;//from www .  java 2s. c  om
    String sheetName = (String) this.filenameCombo.getSelectedItem();
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet(sheetName);
    Row headerRow = sheet.createRow(0);
    String[] headers = exportData.get(0);
    int numOfColumns = headers.length;
    for (int i = 0; i < numOfColumns; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(headers[i]);
    }

    int rowCount = exportData.size();
    for (int rownum = 1; rownum < rowCount; rownum++) {
        Row row = sheet.createRow(rownum);
        String[] values = exportData.get(rownum);
        for (int i = 0; i < numOfColumns; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(values[i]);
        }
    }

    String defaultFilename = "Export.xlsx";
    JFileChooser f = new JFileChooser(System.getProperty("user.dir"));
    f.setSelectedFile(new File(defaultFilename));
    f.setDialogTitle("Wybierz nazw dla pliku eksportu");
    f.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter ff = new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.getName().endsWith(".xlsx"))
                return true;
            return false;
        }

        @Override
        public String getDescription() {
            return "";
        }
    };
    f.setFileFilter(ff);

    File file = null;
    int save = f.showSaveDialog(this);
    if (save == JFileChooser.APPROVE_OPTION)
        file = f.getSelectedFile();
    else
        return;

    FileOutputStream out;
    try {
        out = new FileOutputStream(file);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

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

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);//from   w  ww  .ja v a 2 s  .co  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());

        fileNameSignature = 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);

        txtPathSig.setText(fileNameSignature);

        try {

            File images = new File(fileNameSignature);

            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);
        }

    }
}