Wednesday, April 25, 2012

Java / Eclipse (WindowBuilder plugin) - how do I effectively use Swing Actionlisteners?

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() {

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?

No comments:

Post a Comment