Pregunta

I am trying to load a file from a JFileChooser that is inside a JTabbedPane. I would like the file to load on the click of the 'open' button and also show the file in a different pane. I hope I am explaining myself ok. I have an ActionListener and have tried a few things, but it seems that the code I am using is not firing as it won't even print to the console. Could you please have a look at my code and see where I am going wrong. Thanks

class listener implements ActionListener{
        public void actionPerformed (ActionEvent e)
        {.......// other actions

    else if (e.getSource() instanceof JFileChooser){
            JFileChooser openFile = (JFileChooser)e.getSource();
            String command = e.getActionCommand();
            if (command.equals(JFileChooser.APPROVE_SELECTION)){
                File selectedFile = openFile.getSelectedFile();
                System.out.print("test if working");
                tp.setSelectedIndex(0); //Index of JTab I wand file to load
                loadSavedGame(selectedFile);
                }
            else if (resume.equals(JFileChooser.CANCEL_OPTION)) {
                    //frame.setVisible(true);
                    tp.setSelectedIndex(0);
                }
           }
          }
         }
¿Fue útil?

Solución

The JFileChooser class has an addActionListener(...) method that will accept your ActionListener above. It doesn't have to be shown as a pop-up for it to work.

You never tell us if or how you are adding the ActionListener above to the JFileChooser, but if you are in fact doing this and your code still isn't working, then you'll want to create and post an sscce for us to test and fix.


Edit

Also, I would create the ActionListener to be used with the JFileChooser only and would thus get rid of this line:

else if (e.getSource() instanceof JFileChooser){

If the listener is only added to one object, there's no need to test for the source.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top