Is there a way to properly align text in JCombobox

I want to have a JComboBox with the correct alignment. How can I do it? someone said before: "You can set the render for JComboBox, which can be JLabel with JLabel # setHorizontalAlignment (JLabel.RIGHT)," but I don’t know how to do this?

+7
java swing jcombobox renderer right-align
source share
3 answers

someone said before: "You can install the renderer in a JComboBox, which can be JLabel with JLabel # setHorizontalAlignment (JLabel.RIGHT)"

Yes, the default renderer is JLabel, so you do not need to create your own renderer. You can simply use:

((JLabel)comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT); 
+13
source share

Well, you can do with ListCellRenderer, for example:

 import java.awt.Component; import java.awt.ComponentOrientation; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.SwingUtilities; public class ComboboxDemo extends JFrame{ public ComboboxDemo(){ JComboBox<String> comboBox = new JComboBox<String>(); comboBox.setRenderer(new MyListCellRenderer()); comboBox.addItem("Hi"); comboBox.addItem("Hello"); comboBox.addItem("How are you?"); getContentPane().add(comboBox, "North"); setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); } private static class MyListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); return component; } } public static void main(String [] args){ SwingUtilities.invokeLater(new Runnable() { public void run() { new ComboboxDemo().setVisible(true); } }); } } 
+6
source share

It worked for me beautifully and shortly.

 comboFromDuration.setRenderer(new DefaultListCellRenderer() { @Override public void paint(Graphics g) { setHorizontalAlignment(DefaultListCellRenderer.CENTER); setBackground(Color.WHITE); setForeground(Color.GRAY); setEnabled(false); super.paint(g); } }); 

To avoid customization every time you call Graphics, you can also use an anonymous constructor block:

 comboFromDuration.setRenderer(new DefaultListCellRenderer() { { setHorizontalAlignment(DefaultListCellRenderer.CENTER); setBackground(Color.WHITE); setForeground(Color.GRAY); setEnabled(false); } }); 
0
source share

All Articles