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.smanempat.controller.ControllerClassification.java

public void chooseFile(ActionEvent evt, JTextField txtFileDirectory, JTextField txtNumberOfK,
        JLabel labelJumlahData, JButton buttonProses, JTable tablePreview) {
    try {//from   w  w w  . ja v a2  s .  c  o  m
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Excel File", "xls",
                "xlsx");
        fileChooser.setFileFilter(fileNameExtensionFilter);

        if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
            txtFileDirectory.setText(fileChooser.getSelectedFile().getAbsolutePath());
            System.out.println("Good, File Chooser runing well!");
            if (txtFileDirectory.getText().endsWith(".xls") || txtFileDirectory.getText().endsWith(".xlsx")) {
                showOnTable(evt, txtFileDirectory, tablePreview);
                labelJumlahData.setText(tablePreview.getRowCount() + " Data");
                txtNumberOfK.setEnabled(true);
                txtNumberOfK.requestFocus();
                buttonProses.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(null,
                        "File dataset harus file spreadsheet dengan ekstensi *xls atau *.xlsx!", "Error",
                        JOptionPane.INFORMATION_MESSAGE, new ImageIcon("src/com/smanempat/image/fail.png"));
                txtFileDirectory.setText("");
                chooseFile(evt, txtFileDirectory, txtNumberOfK, labelJumlahData, buttonProses, tablePreview);
            }

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

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Ask the user for a certain file path/*from  ww  w  .  ja v a2  s . c o m*/
 * 
 * @param chooser the {@link JFileChooser} to use
 * @param filter the file filter
 * @param title the title of the dialog
 * 
 * @return the selected file or null
 */
private String askForPath(JFileChooser chooser, FileFilter filter, String title) {
    chooser.setDialogTitle(title);
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile().getAbsolutePath();
    }

    return null;
}

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//from www .  j  a v a2 s.  c  om
            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:coreferenceresolver.gui.MainGUI.java

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

    if (inputFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        testingFilePathTF/*  w  ww. ja  va  2 s. c  o m*/
                .setText(inputFileChooser.getSelectedFile().getAbsolutePath() + File.separator + "test.arff");
        noteTF.setText("Create testing file waiting ...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TrainingMain.run(inputFilePathTF.getText(), markupFilePathTF.getText(),
                            testingFilePathTF.getText(), false);
                    noteTF.setText("Create testing file done!");
                    String folderPathOpen = testingFilePathTF.getText().substring(0,
                            testingFilePathTF.getText().lastIndexOf(File.separatorChar));
                    Desktop.getDesktop().open(new File(folderPathOpen));
                } catch (Exception ex) {
                    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    } else {
        noteTF.setText("No testing file location selected");
    }
}

From source file:coreferenceresolver.gui.MainGUI.java

private void trainingBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trainingBtnActionPerformed
    // TODO add your handling code here:
    JFileChooser inputFileChooser = new JFileChooser(defaulPath);
    inputFileChooser.setDialogTitle("Choose where your training file saved");
    inputFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    if (inputFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        trainingFilePathTF/*from   www  .  ja  va2 s  .co  m*/
                .setText(inputFileChooser.getSelectedFile().getAbsolutePath() + File.separator + "train.arff");
        noteTF.setText("Create training file waiting ...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TrainingMain.run(inputFilePathTF.getText(), markupFilePathTF.getText(),
                            trainingFilePathTF.getText(), true);
                    noteTF.setText("Create training file done!");
                    String folderPathOpen = trainingFilePathTF.getText().substring(0,
                            trainingFilePathTF.getText().lastIndexOf(File.separatorChar));
                    Desktop.getDesktop().open(new File(folderPathOpen));
                } catch (Exception ex) {
                    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    } else {
        noteTF.setText("No training file location selected");
    }
}

From source file:com.mycompany.zad1.MainWindow.java

private int[][] loadMask() {
    JFileChooser chooser = new JFileChooser();
    int dialogResult = chooser.showOpenDialog(this);
    ArrayList<String> fileLines = new ArrayList<>();
    if (dialogResult == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {//w  w w.j  av a  2 s.c  o m
            FileReader fileReader = new FileReader();
            fileLines = fileReader.readMask(file);
        } catch (Exception ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    Parser parser = new Parser();
    int[][] mask = parser.parseMask(fileLines);
    return mask;
}

From source file:EnhancedFileTester.java

public EnhancedFileTester() {
    JButton jb = new JButton("Open File Viewer");
    add(jb);//from w  ww.j a v  a 2s .com
    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser(".");
            FileFilter type1 = new ExtensionFilter("Java source", ".java");
            FileFilter type2 = new ExtensionFilter("Image files",
                    new String[] { ".jpg", ".gif", "jpeg", "xbm" });
            FileFilter type3 = new ExtensionFilter("HTML files", new String[] { ".htm", ".html" });
            chooser.addChoosableFileFilter(type1);
            chooser.addChoosableFileFilter(type2);
            chooser.addChoosableFileFilter(type3);
            chooser.setFileFilter(type2); // Initial filter setting
            FileView view = new IconView();
            chooser.setFileView(view);
            int status = chooser.showOpenDialog(EnhancedFileTester.this);
            if (status == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                System.out.println(f);
            }
        }
    };
    jb.addActionListener(listener);
}

From source file:dotaSoundEditor.Controls.ItemPanel.java

@Override
protected File promptUserForNewFile(String wavePath) {
    DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
    String waveString = selectedTreeNode.getUserObject().toString();
    String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", "");

    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav")
            : new FileNameExtensionFilter("MP3s", "mp3");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);//from  w  w  w . j av a2  s  .  c  o m
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());

        int startIndex = -1;
        int endIndex = -1;
        //Get the actual value for the wavestring key-value pair.
        if (waveString.contains("\"wave\"")) {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3);
        } else //Some wavestrings don't have the "wave" at the beginning for some reason
        {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1);
        }
        String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
        String waveStringNormalizedFilePath = waveStringFilePath.substring(0,
                waveStringFilePath.lastIndexOf("\""));
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", "");
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", "");

        Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            if (waveString.contains("//")) {
                waveString = waveString
                        .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), "");
            }
            waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath
                    + "\" //Replaced by: " + chosenFile.getFileName().toString());
            selectedTreeNode.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.emental.mindraider.ui.dialogs.AttachmentJDialog.java

/**
 * Concetructor.//w  w  w  .ja  v a2 s  . c  o m
 * 
 * @param noteResource
 *            The concept resource.
 * @param dragAndDropReference
 *            The drag'n'drop reference.
 */
public AttachmentJDialog(ConceptResource conceptResource, DragAndDropReference dragAndDropReference) {

    super(Messages.getString("AttachmentJDialog.title"));
    this.conceptResource = conceptResource;
    getContentPane().setLayout(new BorderLayout());
    JPanel p, pp;

    p = new JPanel();
    p.setLayout(new BorderLayout());
    JLabel intro = new JLabel("<html>&nbsp;&nbsp;" + Messages.getString("AttachmentJDialog.introduction")
            + "&nbsp;&nbsp;<br><br></html>");
    p.add(intro, BorderLayout.NORTH);
    p.add(new JLabel("<html>&nbsp;&nbsp;" + Messages.getString("AttachmentJDialog.description") + "</html>"),
            BorderLayout.CENTER);
    description = new JTextField(38);
    pp = new JPanel(new FlowLayout(FlowLayout.LEFT));
    pp.add(description);
    p.add(pp, BorderLayout.SOUTH);
    getContentPane().add(p, BorderLayout.NORTH);

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.setBorder(new TitledBorder(Messages.getString("AttachmentJDialog.resource")));

    ButtonGroup attachType = new ButtonGroup();

    JPanel webPanel = new JPanel();
    webPanel.setLayout(new BorderLayout());
    webType = new JRadioButton(Messages.getString("AttachmentJDialog.web"));
    webType.setActionCommand(WEB);
    webType.addActionListener(this);
    webType.setSelected(true);
    attachType.add(webType);
    webPanel.add(webType, BorderLayout.NORTH);
    urlTextField = new JTextField("http://", 35);
    urlTextField.selectAll();
    urlTextField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                attach();
            }
        }

        public void keyReleased(KeyEvent keyEvent) {
        }

        public void keyTyped(KeyEvent keyEvent) {
        }
    });
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(new JLabel("   "));
    p.add(urlTextField);
    webPanel.add(p, BorderLayout.SOUTH);
    mainPanel.add(webPanel, BorderLayout.NORTH);

    JPanel localPanel = new JPanel();
    localPanel.setLayout(new BorderLayout());
    JRadioButton localType = new JRadioButton(Messages.getString("AttachmentJDialog.local"));
    localType.setActionCommand(LOCAL);
    localType.addActionListener(this);
    localPanel.add(localType, BorderLayout.NORTH);
    pathTextField = new JTextField(35);
    pathTextField.setEnabled(false);
    browseButton = new JButton(Messages.getString("AttachmentJDialog.browse"));
    browseButton.setToolTipText(Messages.getString("AttachmentJDialog.browseTip"));
    browseButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            fc.setApproveButtonText(Messages.getString("AttachmentJDialog.attach"));
            fc.setControlButtonsAreShown(true);
            fc.setDialogTitle(Messages.getString("AttachmentJDialog.chooseAttachment"));
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int returnVal = fc.showOpenDialog(AttachmentJDialog.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                pathTextField.setText(file.toString());
            }
        }
    });
    browseButton.setEnabled(false);
    pp = new JPanel();
    pp.setLayout(new BorderLayout());
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(new JLabel("   "));
    pp.add(p, BorderLayout.NORTH);
    p.add(pathTextField);
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.RIGHT));
    p.add(browseButton);
    pp.add(p, BorderLayout.SOUTH);
    localPanel.add(pp, BorderLayout.SOUTH);
    attachType.add(localType);
    mainPanel.add(localPanel, BorderLayout.SOUTH);

    getContentPane().add(mainPanel, BorderLayout.CENTER);

    // buttons
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.CENTER));
    JButton addButton = new JButton(Messages.getString("AttachmentJDialog.attach"));

    p.add(addButton);
    addButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            attach();
        }
    });
    JButton cancelButton = new JButton(Messages.getString("AttachmentJDialog.cancel"));
    p.add(cancelButton);
    cancelButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            AttachmentJDialog.this.dispose();
        }
    });
    getContentPane().add(p, BorderLayout.SOUTH);

    /*
     * drag and drop initialization
     */
    if (dragAndDropReference != null) {
        if (dragAndDropReference.getType() == DragAndDropReference.BROWSER_LINK) {
            urlTextField.setText(dragAndDropReference.getReference());
            localType.setSelected(false);
            webType.setSelected(true);
            enableWebTypeButtons();
        } else {
            pathTextField.setText(dragAndDropReference.getReference());
            localType.setSelected(true);
            webType.setSelected(false);
            enableLocalTypeButtons();
        }
        description.setText(dragAndDropReference.getTitle());
    }

    pack();
    Gfx.centerAndShowWindow(this);
}

From source file:com.jvms.i18neditor.Editor.java

public void showImportDialog() {
    String path = null;//from w w w. java 2  s.  c  o m
    if (resourcesDir != null) {
        path = resourcesDir.toString();
    }
    JFileChooser fc = new JFileChooser(path);
    fc.setDialogTitle(MessageBundle.get("dialogs.import.title"));
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int result = fc.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        importResources(Paths.get(fc.getSelectedFile().getPath()));
    }
}