在 Swing 中使用这个关键字有什么问题?

What is wrong using this keyword in Swing?

我问这个问题是因为 mKorbel's second comment on this question。我一直在使用 this 关键字来调用局部变量、class 的局部组件(例如按钮)和方法 e.t.c。我不确定按照我一直使用的方式使用关键字有什么问题。

don't to use this.whatever in Swing, Java, (in MCV make me some sence), use local variables insted of.

问题:在Swing中使用this.XXX有什么问题?

示例代码

public class SwingTest extends JFrame {

// variables
private String st = "You clicked me";

SwingTest() {
    this.initUI();

}

private void initUI() {
    this.setTitle("Swing Test");
    this.setSize(200, 200);
    this.setLayout(new BorderLayout());
    this.setVisible(true);

    this.clickMe = new JButton("Click"); // What is wrong with using this
                                            // ref here?

    this.add(clickMe);

    this.clickMe.addActionListener((ActionEvent) -> {
        JOptionPane.showMessageDialog(this, this.st);// What is wrong with
                                                        // using this ref
                                                        // here?
        });
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            SwingTest swingTest = new SwingTest();
        }
    });
}

// components
JButton clickMe;
}

clickMe 按钮不需要是字段。它可以是定义 method/constructor 的对话框内的局部变量 JButton clickMe。由于通常会创建许多 GUI 组件并将其添加到 window,它会清理 class,使声明接近使用,并尽可能缩短生命周期(更改 window 内容)。

(说this只是为了指出clickMe的领域性。)