Thursday, June 29, 2023

Horror Code: How to Align two Labels

 This article was originally posted on JRoller on September 13, 2013

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.

Reading these old articles, I can see now that I was never really explicit in my explanations... Here, the real WTF is not that he used a JTextfield instead of a JLabel, although I'm sure the JLabel would have been a better fit. It is rather the use of a BorderLayout constant with a FlowLayout, that luckily would just ignore it. It might be because of a previous try with a BorderLayout, but then, setting all components on the eastern border will not yield the expected behavior...

No comments:

Post a Comment