trouble with actionPerformed
I'm still working on my notepad program and I've just been working on my "Open" button, which opens up a JFileChooser. I looked at this tutorial online and it said that I could write it into the actionPerformed method of my class like so (this code isn't from the tutorial, this is what I wrote based on what I learned from it... it is incomplete because right now I'm just focusing on getting the actual window to open):
Code:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == bOpen) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
fc.requestFocusInWindow();
fc.grabFocus();
if(returnVal == JFileChooser.APPROVE_OPTION) {
try {
File f = fc.getSelectedFile();
Scanner scan = new Scanner(f);
String newText;
}
catch(FileNotFoundException exception) {
}
}
}
}
However, when I use this code and click the open button, nothing happens. Keep in mind that I didn't make an inner class or anything like that, it's just the actionPerformed method of the overall class (Which I made implement ActionListener just for this).
The weird thing is though, when I use it as an inner class and add it as an actionListener to the button itself, it works just fine. This is the successful code I used:
Code:
bOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
fc.requestFocusInWindow();
fc.grabFocus();
if(returnVal == JFileChooser.APPROVE_OPTION) {
try {
File f = fc.getSelectedFile();
Scanner scan = new Scanner(f);
String newText;
}
catch(FileNotFoundException exception) {
}
}
}
});
As you can see, it's the exact same thing as the above, only I attached it to the button instead of using the if statement with the e.getSource().
If anybody could explain why the second way worked and the first didn't, I'd really appreciate it.