javafilejfilechooserjmenu

JFileChooser to open a file from a JMenu


fileItem1is a JMenuItem when i click on fileItem1, this is how you would make it open a file and then just display the name of that file in the JFrame:

// open file
fileItem1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        Component parent = null;
        int returnVal = chooser.showOpenDialog(parent);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
               System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
            }               
            jStyledTextPane.setText("You chose to open this file: " + chooser.getSelectedFile().getName());
        }
    });

Solution

  • The Oracle example is pretty good in my opinion: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

    Here is the implementation:

        int returnVal = fc.showOpenDialog(FileChooserDemo.this);
    
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {
            log.append("Open command cancelled by user." + newline);
        }