Search code examples
javaswingjcheckbox

Having a Left and Right Aligned Label inside a JCheckBox


I'll start with what I want then go from there:

+------------------------------------------+
|[] jCheckBox                       jLabel |
+------------------------------------------+

Basically I would like to have a JCheckBox with 2 segments of text, 1 left aligned and 1 right aligned. I would like the entire box to be clickable and act exactly like a JCheckBox(As in if I press my mouse down it highlights the box ect.).

Now I have tried:

  • Using HTML inside the text box, with a table along the lines of: <html><table width=100%><tr width=100%><td>Left Text</td><td align=right>Right Text</td></tr></table>. This produces [] Left TextRightText without any visual alignment.

  • Adding both the JCheckBox and the JLabel to a panel, however this would require me to implement all the mouse events and call the correct respective methods on the JCheckBox. I put this aside - however I am willing to reconsider if this is the only option

  • Adding the JLabel to the JCheckBox

    • Firstly this caused the JCheckBox to decide to change the font, so that had to be 'adjusted'
    • Secondly, the baselines were off by 1 or 2 pixels, This was fixed by implementing a LayoutManager that placed the JLabel on the baseline.
    • Thirdly, the JLabel overlapped with the JCheckBox text so I ad to adjust my layout manager, however the JCheckBox did not give a correct result from getPreferedSize()(of [1,1]).

So, basically my question is: How should I implement this?


Solution

    • create parent JLabel, JLabel haven't implemented any LayoutManager, then to set there proper LayoutManager, I think that GridLayout (with 2 segments of text, 1 left aligned and 1 right aligned)

    • add there two JLabels with proper alignment (JLabel.setHorizontalAlignment(javax.swing.SwingConstants.XXX);)

    • put together JCheckBox with parent JLabel (JLabel.setLabelFor(JCheckBox);)

    • the same way for MultiIcon in the JLabel