Home / ພື້ນຖານ Desktop app / GUI_Component / Java ComboBox
ສຳລັບ ComboBox / DropDownList ຫຼື JComboBox (javax.swing.JComboBox) ຈັດຢູ່ໃນກຸ່ມຂອງ Component ໃຊ້ສຳລັບສ້າງລາຍການ ComboBox ຫຼື DropDownList ໂດຍລາຍການທີ່ Option ສາມາດກຳນົດໄດ້ຈາກຊຸດຂໍ້ມູນຂອງ Array ເພື່ອນຳມາສະແດງໃນກລາຍການ Option Item ໄດ້ ແລະ ComboBox ມີ Property ທີ່ສຳຄັນຄື ComboBox.getSelectedItem() ຊຶ່ງຈະໃຊ້ສຳລັບການອ່ານຄ່າລາຍການທີ່ຖືກເລືອກ
public class MyForm extends JFrame {
public MyForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 343, 273);
setTitle("Kittisay Java");
setLayout(null);
// Combobox
String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
comboBox.setBounds(113, 76, 107, 20);
add(comboBox);
// Button
JButton btn = new JButton("Button");
btn.addActionListener((e) -> {
JOptionPane.showMessageDialog(null,
"You selected : " + comboBox.getSelectedItem());
});
btn.setBounds(126, 123, 81, 23);
add(btn);
}
public static void main(String[] args) {
MyForm frm = new MyForm();
frm.setVisible(true);
}