How can we set the border to JComboBox items 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 ItemListener interfaces when the user actions on a combo box. We can set the border to the items of a JComboBox by rendering a JComboBox which extends the DefaultListCellRenderer class and need to override the getListCellRendererComponent() method.

Syntax

public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)

Example

import java.awt.*;
import javax.swing.*;

public class JComboBoxTest extends JFrame {
   public JComboBoxTest() {
      setTitle("JComboBox Test");
      String[] cities = {"Hyderabad", "Mumbai", "Pune", "Bangalore", "Chennai", "Coimbatore"};
      JComboBox jcb = new JComboBox(cities);
      jcb.setRenderer(new CustomComboBoxRenderer());
      add(jcb, BorderLayout.NORTH);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   class CustomComboBoxRenderer extends DefaultListCellRenderer {
      public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
         JLabel lbl = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected,  cellHasFocus);
         lbl.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
         lbl.setBackground(Color.lightGray);
         return lbl;
      }
   }
   public static void main(String[] args) {
      new JComboBoxTest();
   }
}

Output

raja
Published on 06-Sep-2019 17:36:24
Advertisements