views:

71

answers:

1

I would like to use factory classes and methods to generate GUI components, but I don't know how and in which class the various listeners should be declared and added to the components.

If I have a simple factory class such as that listed below should I add an ActionListener to the button before it is returned to the calling class. If the answer is "Yes" then how do I add the listener?

class GUIFactory
{
    public static JButton getJButton()
    {
        JButton aButton = new JButton();
        return aButton; 
    }
}

Suppose I wanted to use the getJButton() method to add 5 buttons to the GUI, how would I code the ActionListener so that it would know which button was clicked?

Or should the listeners be added in the calling class?

JFrame gui = new JFrame();
gui.add(AppFactory.getJButton());

I've tried the following

gui.add(GUIFactory.getJButton().addActionListener(new guiButtonListener()));

and got an error:

"void" type not allowed here.

+2  A: 

It's because addActionListener returns void. Try:

JButton button = GUIFactory.getJButton();
button.addActionListener(new guiButtonListener())
gui.add(button);

Be aware that Swing GUI programming is quite idiomatic. Some may prefer using Beans Binding (or other binding solution) to connect views and models with each other. One would argue that using an Event Bus yield the best, lowly coupled, highly reusable GUI components. Have a look also at the Swing Application Framework (now deprecated, but the BSAF for is in very good condition) and GUTS framework.

You'll see there are many attempts to address GUI programming and design issues. The topic is very broad, and solutions vary greatly.

Oh, and the big two Swing Rich Content Platforms (NetBeans RCP, Eclipse RCP) have very specific APIs to deal with GUIs. As an example, NetBeans RCP uses Lookup, Nodes and Windows APIs to shield developer from Swing issues. The Eclipse team ditched Swing and wrote their own SWT GUI toolkit. You might want to look at tutorials if You'd wanted some great design references.

Rekin
Eclipse RCP is not based upon Swing!
Johannes Wachter
Hi there, Rekin. Thanks for the answer - I could've kicked myself when I saw your code sample :-) I have no experience of using factories so was just trying my hand based on other code samples I'd read here on SO Thanks.
The Thing