JLabel Right-Handed Badge and Text

Is it possible to create a JLabel with a right-handed icon and text, and the icon on the right, for example:

enter image description here

I saw this question, but is this really the best approach?

+7
source share
2 answers

Perhaps this will be more than what you are looking for? It should align everything on the right side of the panel (more than the example you were looking for):

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; } } 
+9
source

The above example uses layout and label properties to align left / right.

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

image

+6
source

All Articles