How to get the selected value from a dropdown list in Java?

To retrieve the selected value from a ComboBox in Java, you can achieve it by following these steps:

  1. Obtain the dropdown list object:
JComboBox comboBox = new JComboBox();
// 添加下拉列表选项
comboBox.addItem("Option 1");
comboBox.addItem("Option 2");
comboBox.addItem("Option 3");
  1. Add selection listener:
comboBox.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // 获取选中的值
        String selectedValue = (String) comboBox.getSelectedItem();
        System.out.println("Selected Value: " + selectedValue);
    }
});

By following the above steps, you can instantly retrieve and process the selected value when a user picks an option from the dropdown list.

广告
Closing in 10 seconds
bannerAds