javaswingjcombobox

Is there a way to center only the selected item in a JComboBox (so keep all items in the combo box left-aligned)


I know there is a simple way to center all the items in the JComboBox, but i have searched StackOverflow and across the web and there is no talk about how to center the selected item only.

To make it clear, when I select an item from the combo box, this box closes the list and shows the selected item only. It is this item I want centered.

Is there a way to do it?


Solution

  • This is controlled by the renderer.

    The selected item is renderered when the index passed to the renderer is -1.

    You can create a custom renderer and change the alignment of the text based on the index:

    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicComboBoxRenderer;
    
    public class ComboRenderer
    {
       public void makeUI()
       {
          JComboBox<String> comboBox = new JComboBox<>(new String[]{"A", "B", "C"});
    
          comboBox.setRenderer(new BasicComboBoxRenderer()
          {
             @Override
             public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
             {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    
                setHorizontalAlignment( index == -1 ? JLabel.CENTER : JLabel.LEFT );
    
                return this;
             }
          });
    
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(comboBox);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args)
       {
          SwingUtilities.invokeLater(() -> new ComboRenderer().makeUI() );
       }
    }