Java JFrame创建关闭按钮

时间:2013-10-17 18:53:41

标签: java swing jframe

我写了一个表格,通过浏览各种资源,我们想出了一个可以在按下“X”时自行关闭的表格。但是,我似乎是以一种相当黑客的方式做到了。

(我发布的代码已经条纹化了不相关的化妆品细节,但它本质上是基于本教程的弹出式通知: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);
    }
}

我似乎无法在actionPerformed方法中使用“this”而不引用其他内容。我做了一个System.out.println(this.getClass());,它给了我class Notification$1。所以我尝试将其转换为Notification对象,但是eclipse给出了一个错误说明Cannot cast from new ActionListener(){} to Notification

我设置它的方式有效并且似乎没有任何问题,但这似乎也不是好的做法。有一个更好的方法吗?谢谢大家。

2 个答案:

答案 0 :(得分:4)

使用

Notification.this.dispose();

只需使用this即可ActionListener


非常类似于:Getting hold of the outer class object from the inner class object

答案 1 :(得分:2)

通过访问事件的源对象来编写更多通用代码:

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

现在您可以在任何GUI中使用此ActionListener,因为您没有将类名称硬编码为代码的一部分。