1

我正在尝试从 JTabbedPane 内的 JFileChooser 加载文件。我希望在单击“打开”按钮时加载文件,并在不同的窗格中显示文件。我希望我能很好地解释自己。我有一个 ActionListener 并尝试了一些事情,但似乎我正在使用的代码没有触发,因为它甚至不会打印到控制台。你能否看看我的代码,看看我哪里出错了。谢谢

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

1 回答 1

2

JFileChooser 类有一个addActionListener(...)方法可以接受上面的 ActionListener。它不必显示为弹出窗口即可工作。

您永远不会告诉我们您是否或如何将上面的 ActionListener 添加到 JFileChooser,但如果您实际上正在这样做并且您的代码仍然无法正常工作,那么您将需要创建并发布一个sscce供我们测试和使固定。


编辑

此外,我将创建仅与 JFileChooser 一起使用的 ActionListener ,因此将摆脱这一行:

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

如果监听器只添加到一个对象,则无需测试源。

于 2013-10-11T12:17:01.020 回答