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