Note that there are some explanatory texts on larger screens.

plurals
  1. POAlign a JLabel with the text of a JCheckBox
    primarykey
    data
    text
    <p>Is there a look-and-feel-independent way to align a component (e.g. a <code>JLabel</code>) horizontally with the <em>text</em> of a <code>JCheckBox</code>?</p> <p>I am trying to use values from the <code>UIDefaults</code> to predict the location of the text relative to the top-left corner of the <code>JCheckBox</code>. I have found a combination that gives the right result for the Metal, Windows, Motif and Aqua Look-and-Feels:<br> <img src="https://i.stack.imgur.com/x4Y0N.png" alt="Example: Metal (correctly-aligned)"></p> <p>But not in Nimbus:<br> <img src="https://i.stack.imgur.com/LxO0D.png" alt="Example: Nimbus (incorrectly-aligned)"></p> <p>Is there a utility method somewhere that will reliably give X,Y offsets for the text in all Look-and-Feels?</p> <hr> <p>Code (note: to avoid any layout side-effects I used a null layout for this test):</p> <pre><code>import java.awt.Insets; import javax.swing.JApplet; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.border.Border; public class AlignCheckBoxText extends JApplet { public AlignCheckBoxText() { setLayout(null); checkBox = new JCheckBox("Hello, World!"); label = new JLabel("Hello, World!"); add(checkBox); add(label); } @Override protected void validateTree() { checkBox.setLocation(0, 0); checkBox.setSize(checkBox.getPreferredSize()); int labelX = UIManager.getIcon("CheckBox.icon").getIconWidth(); Insets cbInsets = UIManager.getInsets("CheckBox.margin"); if (cbInsets != null) labelX += cbInsets.left + cbInsets.right; Border cbBorder = UIManager.getBorder("CheckBox.border"); if (cbBorder != null) { Insets borderInsets = cbBorder.getBorderInsets(checkBox); if (borderInsets != null) { labelX += borderInsets.left; } } label.setLocation(labelX, checkBox.getHeight()); label.setSize(label.getPreferredSize()); super.validateTree(); } private JCheckBox checkBox; private JLabel label; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload