I’m learning Swing and have composed an interface using a series of get methods to add components. Is it a good practise to add a Listener inside a get method as follows? I’d like to make things as decoupled as possible.
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;
}
From my extensive practice as a Swing developer I can tell you that it’s not good practice to obtain component instances in this manner(via getters). I generally setup the UI for a Frame/Dialog in some method like initComponents() and afterwards add all the listeners in some method like addListeners(). I’m not sure if that there is a single best practice as how to do things – there a lot of options and personal preferences. Generally, however, lazy init of components that you’ll need anyways(like this button I presume) is unneeded.
Also – you should really consider using some layout manager such a MiG and avoid hardcoded component sizes.