My question is specific to Eclipse and the Swing WindowBuilder plugin.
To make simple Swing apps I normally create a class and extend a JFrame. I make my Swing components private class variables. This allows me to add an Actionlisteners and access the swing components in actionPerformed(), like this:
public class MyClass() extends JFrame implements ActionListener {
private JButton btnClickMe = new JButton("Click me");
public MyClass() {
super("title");
this.setLayout(null);
btnClickMe.setBounds(1,1,100,100);
this.add(btnClickMe);
btnClickMe.addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == btnClickMe) { // do something }
}
public static void main(String[] args) {
new MyClass();
}
}
By default the WindowBuilder plugin create Swing component variables I guess in what would be considered the constructor (public MyClass()), rather than private class variables. As a result due to scope I am not able to use ActionListeners the way I am used to since the Swing variables are not visible to actionPerformed().
Can anyone advise how this can be overcome?
What’s stopping you from refactoring those local variables to fields? One of the best things about WindowBuilder is able to parse hand written code to some extent.
Besides, there’s a configuration option in Window Builder to create field variables for controls. Look in Eclipse,
Preferences->WindowBuilder->Swing->Code generation😉