Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLabel Right-Justified Icon and Text

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?

like image 292
Edward Ruchevits Avatar asked Aug 19 '12 15:08

Edward Ruchevits


People also ask

How do you change the alignment of a label in Java?

This can be done in two ways. To align to the right: JLabel label = new JLabel("Telephone", SwingConstants. RIGHT);

How do I get JLabel to text next line?

Surround the string with <html></html> and break the lines with <br/> . just a little correction: use <br /> instead of just <br> ... this is recommended way of doing it (to not miss any closing tags)...


2 Answers

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;
    }
}
like image 115
Nick Rippe Avatar answered Oct 11 '22 05:10

Nick Rippe


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

like image 37
trashgod Avatar answered Oct 11 '22 04:10

trashgod