Or rather how not to. This is a code a colleague found on our GUI. The developper probably did not know how to align two components, so he decided to do it his own way. There is no easy way to set the size of a JLabel, but there is a constructor for JTextfield on which you can set a size in number of characters. So he took a JTextfield, removed the border, set it as non editable, and it becomes magically a JLabel to the outside world.
final JPanel lbgpanel = new JPanel(); lbgpanel.setLayout(new FlowLayout(FlowLayout.LEFT)); final JTextField lbgLabel = new JTextField("Background :", 7); lbgLabel.setBorder(null); lbgLabel.setEditable(false); lbgpanel.add(lbgLabel, BorderLayout.EAST); lbgpanel.add(_colorBackgroundBt, BorderLayout.EAST); lbgpanel.add(_resetBg, BorderLayout.EAST); final JPanel lfgpanel = new JPanel(); lfgpanel.setLayout(new FlowLayout(FlowLayout.LEFT)); final JTextField lfgLabel = new JTextField("Foreground :", 7); lfgLabel.setBorder(null); lfgLabel.setEditable(false); lfgpanel.add(lfgLabel, BorderLayout.EAST); lfgpanel.add(_colorForeGroundBt, BorderLayout.EAST); lfgpanel.add(_resetFg, BorderLayout.EAST);
As a side note, I never understood the use of the BoderLayout.EAST constant in a FlowLayout.