JButton和JFileChooser的错误消息

时间:2013-05-14 22:18:53

标签: java swing jbutton runtime-error jfilechooser

我想要一个带有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)

2 个答案:

答案 0 :(得分: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();
            ...
        }
    }
});

答案 1 :(得分:1)

ActionListener接口定义了一个名为actionPerformed的方法。您的课程中有两种方法,一种称为actionPerformed,另一种称为ActionPerformed。被调用的是接口中定义的那个,即actionPerformed。你的类中有这样一个方法,它的唯一声明是抛出UnsupportedOperationException。永远不会调用包含实际代码的ActionPerformed方法。

解决方案:

删除存根actionPerformed方法,并将ActionPerformed的名称更改为actionPerformed。或者(虽然不推荐),让actionPerformed调用ActionPerformed