问题
I want to have a button with a JFileChooser action. This is the code that I wrote:
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 {
}
}
}
but the problem is that when I run it, I got a long error message that is part of:
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)
回答1:
The ActionListener here is explicitly throwing an UnsupportedOperationException. Move the JFileChooser functionality into the 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();
...
}
}
});
回答2:
The ActionListener interface defines a method called actionPerformed. You have two methods in your class, one called actionPerformed and another called ActionPerformed. The one that gets invoked is the one defined in the interface, namely actionPerformed. You have such a method in your class whose only statement is to throw an UnsupportedOperationException. The ActionPerformed method, which contains the real code, is never called.
Solution:
Strip out the stub actionPerformed method and change the name of ActionPerformed to actionPerformed. Alternatively (though not recommended), make actionPerformed invoke ActionPerformed.
来源:https://stackoverflow.com/questions/16553778/error-message-with-jbutton-and-jfilechooser