如何在 Java 中设置 JComboBox 选项的框线?
JComboBox 是JComponent 类的子类,它是一个 **文本域** 和 **下拉列表** 的组合,用户可以从中选择一个值。当用户对组合框操作时,JComboBox 可以生成ActionListener、ChangeListener 和**ItemListener 接口。通过呈现一个JComboBox (它扩展了**DefaultListCellRender** 类)并覆盖**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(); } }
输出
广告