I've found this answer on SO and was confused about it.
We have a question about someone who wants to know how to dispose of a JDialog within an ActionListener.
try this way:
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
and then
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
This is the code that the person who answered has posted (here's the link to the question)
Here's what I'm doing in my own code :
buttonCancel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
But I really am concerned about the answer above. Am I doing something wrong or doesn't it change anything if done like that? If it doesn't have an impact, would you know why the person answered by using an intermediate method?
Thank you
I assume that your contains in MyDialog
class
whichextends
JDialog
Consider your following code.
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
You have created an anonymous inner class of java.awt.event.ActionListener
. If you use this
keyword inside the the anonymous inner class it allows to access it self, but not MyDialog
class
as you expected. Therefore this.dispose()
method is not available. But you can access it as MyDialog.this.dispose();
Look at your second example
buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
Of course, ActionListener
is also an anonymous inner class here. But it allows to access methods of it's containing class. So, it's possible to use dispose()
method here.