Working with JFileChooser - getting access to the selected file

14,704

How about defining your File file variable at the class level instead of inside the anon inner class?

public class SwingSandbox {

  private File file;

  public SwingSandbox() {
    final JFrame frame = new JFrame("Hello");

    JButton btnFile = new JButton("Select Excel File");
    btnFile.addActionListener(new ActionListener() {
        //Handle open button action.
        public void actionPerformed(ActionEvent e) {
            final JFileChooser fc = new JFileChooser(); 
            int returnVal = fc.showOpenDialog(frame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
                //This is where a real application would open the file.
                System.out.println("File: " + file.getName() + ".");    
            } else {
                System.out.println("Open command cancelled by user.");
            }
            System.out.println(returnVal);
        }
    });

    frame.getContentPane().add(btnFile);
    frame.setSize(100, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }


  public static void main(String[] args) throws Exception {
    new SwingSandbox();
  }

}
Share:
14,704
Colm Shannon
Author by

Colm Shannon

Graduate looking for work in Ireland

Updated on June 04, 2022

Comments

  • Colm Shannon
    Colm Shannon almost 2 years

    havn't coded in a while so think I'm a bit rusty. I'm trying to build an app that lets a user select a file as input. The following bit of code is what I have at the moment:

    JButton btnFile = new JButton("Select Excel File");
    btnFile.addActionListener(new ActionListener() {
        //Handle open button action.
        public void actionPerformed(ActionEvent e) {
            final JFileChooser fc = new JFileChooser(); 
            int returnVal = fc.showOpenDialog(frmRenamePdfs);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                System.out.println("File: " + file.getName() + ".");    
            } else {
                System.out.println("Open command cancelled by user.");
            }
            System.out.println(returnVal);
        }
    });
    

    I can't seem to figure out how to get access to "file" from outside of the Listener, i.e. in the function where the rests of the GUI is created. I have a blank text label adjacent to the button that launches the file chooser, so what I want to do is store the file, and also set the text of the text label to the name of the file.