Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to right-justify icon in a JLabel?
    text
    copied!<p>For a JLabel with icon, if you <code>setHorizontalTextPosition(SwingConstants.LEADING)</code>, the icon is painted right after text, no matter how wide the label is.</p> <p>This is particularly bad for a list, as the icons would be all over the place depending on how long the text is for each item.</p> <p>I traced the code and it seems to be that in <code>SwingUtilities#layoutCompoundLabelImpl</code>, text width is simply set to <code>SwingUtilities2.stringWidth(c, fm, text)</code>, and icon x is set to follow text without considering label width.</p> <p>Here is the simplest case:</p> <pre><code>import java.awt.*; import javax.swing.*; public class TestJLabelIcon { public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { JLabel c = new JLabel("abc"); c.setHorizontalTextPosition(SwingConstants.LEADING); c.setHorizontalAlignment(SwingConstants.LEADING); c.setIcon(UIManager.getIcon("FileChooser.detailsViewIcon")); c.setBorder(BorderFactory.createLineBorder(Color.RED)); JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.getContentPane().add(c); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } </code></pre> <p>You can see that label always fills the frame but icon stays put. You'll get the mirror problem if you set both arguments to <code>TRAILING</code>.</p> <p>I know I can override the UI, or use a JPanel, etc. I just wonder if I'm missing something simple in JLabel. If not, it seems like a Java bug.</p> <p>FYI this is jdk1.6.0_06 on Windows XP.</p>
 

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