A JComboBox เป็นคลาสย่อยของ JComponent class และมันคือการรวมกันของ text field และ รายการแบบเลื่อนลง ซึ่งผู้ใช้สามารถเลือกค่าได้ JComboBox สามารถสร้าง ActionListener, ChangeListener และ ItemListener อินเทอร์เฟซเมื่อผู้ใช้ดำเนินการกับกล่องคำสั่งผสม เราสามารถกำหนดเส้นขอบให้กับรายการของ JComboBox โดยการแสดงผล JComboBox ซึ่งขยาย DefaultListCellRenderer และจำเป็นต้องแทนที่ getListCellRendererComponent() วิธีการ
ไวยากรณ์
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();
}
} ผลลัพธ์
