0

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.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
Niko
  • 4,158
  • 9
  • 46
  • 85

2 Answers2

4

Use

Notification.this.dispose();

Just using this refers to the ActionListener.


Fairly similar to: Getting hold of the outer class object from the inner class object

Community
  • 1
  • 1
Obicere
  • 2,999
  • 3
  • 20
  • 31
2

Write more generic code by accessing the source object of the event:

Window window = SwingUtilities.windowForComponent((Component)e.getSource());  
window.dispose();

Now you can use this ActionListener in any GUI because you haven't hardcode the class name as part of the code.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • So I came across this again, I remembered that I had asked this question before so I looked it back up. Going over these two answers I realize now that this should have actually been the chosen answer the first time around. Thanks for this – Niko Jun 27 '14 at 18:28
  • `I realize now that this should have actually been the chosen answer the first time around.` - thanks, better late than never ;) – camickr Jun 27 '14 at 19:10