0

我想要一个带有 JFileChooser 操作的按钮。这是我写的代码:

public class Main {

private static String fullPath;
private JFileChooser inputFile;

public static void main(String args[]) throws FileNotFoundException, IOException {
    try {

        GridBagConstraints gbc = new GridBagConstraints();

        JButton inputButton = new JButton("Browse input file");

        myPanel.add(inputButton, gbc);

        inputButton.addActionListener(new ActionListener() {
        public void ActionPerformed(ActionEvent e) {
        JFileChooser inputFile = new JFileChooser();
        inputFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        File file1 = inputFile.getSelectedFile();
        String fullpathTemp = (String) file1.getAbsolutePath();
        fullPath = fullpathTemp;
            }
                public void actionPerformed(ActionEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });


} catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    } finally {
    }
}
}

但问题是,当我运行它时,我收到一条很长的错误消息,它是以下内容的一部分:

Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException: Not     supported yet.
at main.Main$1.actionPerformed(Main.java:200)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
4

2 回答 2

2

这里ActionListener明确抛出一个UnsupportedOperationException. 将JFileChooser功能移动到ActionListener

input_button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JFileChooser inputFile = new JFileChooser();
        inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if (inputfile.showOpenDialog(myFrame) == JFileChooser.APPROVE_OPTION) {
            File file1 = inputFile.getSelectedFile();
            String fullpathTemp = (String) file1.getAbsolutePath();
            ...
        }
    }
});
于 2013-05-14T22:22:33.753 回答
1

ActionListener接口定义了一个名为actionPerformed. 你的类中有两种方法,一种是被调用的actionPerformed,另一种是被调用ActionPerformed的。被调用的是接口中定义的那个,即actionPerformed. 你的类中有这样一个方法,它唯一的语句就是抛出一个UnsupportedOperationException. ActionPerformed包含真实代码的方法永远不会被调用。

解决方案:

剥离存根actionPerformed方法并将名称更改ActionPerformedactionPerformed。或者(虽然不推荐),actionPerformed调用ActionPerformed

于 2013-05-14T22:27:10.743 回答