我正在学习Swing,并且已经使用一系列get方法添加了组件来构成一个接口。如下所示,在get方法内添加侦听器是一种好习惯吗?我想使事情尽可能地分离。
private JButton getConnectButton() {
if (connectButton == null) {
connectButton = new JButton();
connectButton.setText("Connect");
connectButton.setSize(new Dimension(81, 16));
connectButton.setLocation(new Point(410, 5));
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// actionPerformed code goes here
}
});
}
return connectButton;
}
最佳答案
从我作为Swing开发人员的广泛实践中,我可以告诉您,以这种方式(通过getters)获取组件实例不是一个好习惯。通常,我通常使用诸如initComponents()之类的方法为框架/对话框设置UI,然后以诸如addListeners()之类的方法添加所有侦听器。我不确定是否有唯一的最佳做法来做事-有很多选择和个人喜好。但是,通常来说,不需要您惯用的组件的惰性初始化(例如我假定的此按钮)。
另外-您应该真正考虑使用诸如MiG之类的布局管理器,并避免使用硬编码的组件大小。