7

Is it possible to create a JLabel with a right-justified icon and text and the icon is on the right, like this:

enter image description here

I've seen this question, but is it really the best approach?

Community
  • 1
  • 1
Edward Ruchevits
  • 6,411
  • 12
  • 51
  • 86
  • Also consider a `JList` or `JTable` [renderer](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender). – trashgod Aug 19 '12 at 15:34
  • 3
    Here's a related [example](http://stackoverflow.com/a/7620726/230513) for tinkering. – trashgod Aug 19 '12 at 15:41
  • 2
    That answer is given by one of **THE BEST** in Java Swing :-) You name it and the person has one example coming to you from the **MAGIC BOX** – nIcE cOw Aug 19 '12 at 15:43
  • 1
    @GagandeepBali: You are too kind. This related [example](http://stackoverflow.com/a/2834484/230513) illustrates using an `Icon` in a renderer. – trashgod Aug 19 '12 at 15:46
  • 3
    Found another good trashgod sample :) :http://stackoverflow.com/questions/2932389/how-to-right-justify-icon-in-a-jlabel – David Kroukamp Aug 19 '12 at 15:49

2 Answers2

9

Perhaps this would be more what you're looking for? It should align everything on the right side of the panel (more so than the example you were looking at):

Screenshot of Code

import java.awt.*;
import javax.swing.*;

public class TempProject
{
    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                Box mainContent = Box.createVerticalBox();
                mainContent.add(TempProject.getLabel("abc"));
                mainContent.add(TempProject.getLabel("Longer"));
                mainContent.add(TempProject.getLabel("Longerest"));
                mainContent.add(TempProject.getLabel("Smaller"));

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                frame.setContentPane(mainContent);    
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static JLabel getLabel(String text){
        JLabel c = new JLabel(text);
        c.setHorizontalTextPosition(SwingConstants.LEADING);
        c.setAlignmentX(SwingConstants.RIGHT);
        c.setIcon(UIManager.getIcon("FileChooser.detailsViewIcon"));
        return c;
    }
}
Nick Rippe
  • 6,465
  • 14
  • 30
6

The example cited uses layout and label properties for right/left justification.

Additionally, consider implementing the Icon interface in a JList renderer, where setHorizontalAlignment() and setVerticalAlignment() may be used to control the relative geometry. This related TableCellRenderer illustrates the principle.

image

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
trashgod
  • 203,806
  • 29
  • 246
  • 1,045