0

私はフォームを作成し、さまざまなリソースを調べて、「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。だから私はそれを通知オブジェクトにキャストしようとしましたが、Eclipseは私にエラーを示しCannot cast from new ActionListener(){} to Notificationます.

私がセットアップした方法は機能し、問題はないようですが、これも良い習慣とは思えません。これを行うより良い方法はありますか?皆さんありがとう。

4

2 に答える 2

4

使用する

Notification.this.dispose();

を使用するだけthisで、ActionListener.


かなり似ています:内部クラス オブジェクトから外部クラス オブジェクトを取得する

于 2013-10-17T18:55:56.947 に答える