How to center align the items of a JComboBox in Java?


A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener and an ItemListener when the user actions on a combo box. By default, items in the JCombobox are left-aligned, we can also change to center alignment by using the setHorizontalAlignment(DefaultListCellRenderer.CENTER) method of DefaultListCellRenderer class.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxAlignmentTest extends JFrame {
   private JComboBox comboBox;
   private DefaultListCellRenderer listRenderer;
   public JComboBoxAlignmentTest() {
      setTitle("JComboBoxAlignment Test");
      setLayout(new FlowLayout());
      Object[] items = new Object[] {"item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7"};
      comboBox = new JComboBox(items);
      add(comboBox);
      listRenderer = new DefaultListCellRenderer();
      listRenderer.setHorizontalAlignment(DefaultListCellRenderer.CENTER); // center-aligned items
      comboBox.setRenderer(listRenderer);
      setSize(375, 250);
      setResizable(false);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String []args) {
      new JComboBoxAlignmentTest();
   }
}

Output

Updated on: 10-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements