I am asking this question due to mKorbel's second comment on this question . I have been using this
keyword to call local variables, local components of that class (example Buttons) and methods etc I am not sure what is wrong with using the keyword the way I have been doing it.
don't to use this.whatever in Swing, Java, (in MCV make me some sence), use local variables insted of.
Question: What is wrong with using this.XXX
in Swing?
Sample Code
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;
}
The button clickMe does not need to be a field. It can be a local variable JButton clickMe
inside the dialog defining method/constructor. As normally many GUI components are created and added to the window, it cleans up the class, keeps declarations close to usage, and leaves the life-time as short as possible (on changing window contents).
(The talk about this
is merely to point out the fieldness of clickMe
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.