Using static factory classes to generate GUI components - How and where to add the required listeners?

萝らか妹 提交于 2019-12-12 09:44:18

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3543419/using-static-factory-classes-to-generate-gui-components-how-and-where-to-add-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!