如何在 Java 中设置 JComboBox 项目的边框?
awtjavaobject oriented programmingprogrammingswing
JComboBox 是 JComponent 类的子类,它是 text 字段和 下拉列表的组合,用户可以从中选择一个值。当用户对组合框执行操作时,JComboBox 可以生成 ActionListener、ChangeListener 和 ItemListener 接口。我们可以通过呈现 JComboBox (扩展 DefaultListCellRenderer 类并需要覆盖 getListCellRendererComponent() 方法)来设置 JComboBox 项目的边框。
语法
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
示例
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(); } }