我们如何在Java中为JComboBox项设置边框?

How can we set the border to JComboBox items in Java?

句法

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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();
 }
}

输出量