Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

From source file:com.mirth.connect.client.ui.panels.export.MessageExportPanel.java

private void browseSelected() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    if (userPreferences != null) {
        File currentDir = new File(userPreferences.get("currentDirectory", ""));

        if (currentDir.exists()) {
            chooser.setCurrentDirectory(currentDir);
        }//www. j av a2  s  .  c o  m
    }

    if (chooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
        if (userPreferences != null) {
            userPreferences.put("currentDirectory", chooser.getCurrentDirectory().getPath());
        }

        rootPathTextField.setText(chooser.getSelectedFile().getAbsolutePath());
    }
}

From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileGraphicDetailPanel.java

private Component createImportButton() {
    JButton b = new JButton(new AbstractAction(null, UIAgent.getInstance().getIcon(UIAgent.ICON_IMPORT_24)) {

        private static final long serialVersionUID = 985413615438877711L;

        @Override//w  ww  . jav a2  s. c  o  m
        public void actionPerformed(ActionEvent e) {
            JFileChooser ch = new JFileChooser();
            ch.setFileFilter(new ExtensionFilter("xls", "Excel File"));
            int i = ch.showOpenDialog(null);
            if (i == JFileChooser.APPROVE_OPTION) {
                DiveProfileExcelParser p = new DiveProfileExcelParser();
                try {
                    File f = ch.getSelectedFile();
                    DiveProfile dp = p.read(f);
                    I18nResourceManager i18n = I18nResourceManager.sharedInstance();
                    int yes = JOptionPane.showConfirmDialog(DiveProfileGraphicDetailPanel.this,
                            i18n.getString("overwritte.diveprofile.confirm"), i18n.getString("confirmation"),
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (yes == JOptionPane.YES_OPTION) {
                        currentDive.setDiveProfile(dp);
                        setDiveProfile(dp, currentDive);
                        logBookManagerFacade.setDiveChanged(currentDive);
                    }
                } catch (IOException e1) {
                    ExceptionDialog.showDialog(e1, DiveProfileGraphicDetailPanel.this);
                    LOGGER.error(e1.getMessage());
                }
            }

        }
    });
    b.setToolTipText("Import");
    return b;
}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Gets the show to open and opens the respective json file.
 *///from  ww w.  j a  v  a 2 s . c  om
private void openShow() {
    if (askToSave()) {

        File file;
        final JFileChooser fc = new JFileChooser(Main.getFilePath());
        fc.setFileFilter(new DrillFileFilter());
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal;
        do {
            returnVal = fc.showOpenDialog(this);
            file = fc.getSelectedFile();
        } while (returnVal != JFileChooser.CANCEL_OPTION && returnVal != JFileChooser.ERROR_OPTION
                && !file.exists());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                String name, path;
                path = file.getCanonicalPath();
                path = path.substring(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1);
                name = file.getName().toLowerCase().endsWith(".drill") ? file.getName()
                        : file.getName() + ".drill";
                Main.setFilePath(path);
                Main.setPagesFileName(name);
                Main.load(false);
                desktop.createNewInternalFrames();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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

public MusicFrame(JFrame frame, final GeneralSave gs) {

    ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
    try {//  w  w w . j ava 2 s  . co 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: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);/* w  w  w. jav  a2s.  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());

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

    }
}

From source file:frames.MainGUI.java

private File getSelectedFile() {
    // get file path
    FileFilter filter = new FileNameExtensionFilter("soccer data files", "csv");

    JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));

    chooser.addChoosableFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    } else//  w  w  w .  j a v a 2s .  c  o m
        return null;
}

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  .j av  a 2s .  c om
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: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);/*from  w  w  w  .j a v a2 s. c  om*/
    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:com.sciaps.view.SpectrometerStackPanel.java

public void getRegionTextFile() {

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "TXT"));
    int retval = fileChooser.showOpenDialog(Constants.MAIN_FRAME);

    if (retval == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();

        try {// w w  w  .  j a  va  2 s.  co m
            FileReader fr = new FileReader(file.getAbsoluteFile());
            BufferedReader br = new BufferedReader(fr);

            StringBuilder text = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
            }

            br.close();

            createRegionItem(text.toString());

        } catch (FileNotFoundException ex) {
            showErrorDialog(ex.getMessage());
        } catch (IOException ex) {
            showErrorDialog(ex.getMessage());
        }

    }

}

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//from www . j a  v a2 s  . co  m
        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");
    }

}