I've written a form and through looking through various resources have come up with a form that can close itself when "X" is pressed. However, I seem to have done it in a fairly hack-tastic way.
(The code I'm posting has been striped of the non-relevant cosmetic details, but it is in-essence a pop-up notification based on this tutorial: http://harryjoy.me/2011/07/01/create-new-message-notification-pop-up-in-java/)
public class Notification extends JFrame {
private JFrame uglyJFrameHack;
public Notification(String header, String message) {
super();
uglyJFrameHack = this;
JButton closeBtn = new JButton("X");
closeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
uglyJFrameHack.dispose(); //here's where this all seems screwy.
}
});
this.add(closeBtn);
this.setVisible(true);
}
}
I can't seem to use "this" in the actionPerformed method without it referencing something else. I did a System.out.println(this.getClass());
and it gave me class Notification$1
. So I tried to type cast it to a Notification object, but eclipse give me an error stating Cannot cast from new ActionListener(){} to Notification
.
The way I have it setup works and doesn't seem to have any issues, but this also doesn't seem like good practice. Is there a better way to do this? Thanks all.