How can you retrieve the value of a dropdown list box in Java?

In Java, it is common to obtain the value of a dropdown list box by using an event listener. One can create a dropdown list box using Swing or JavaFX and add an event listener to retrieve the selected value.

Here is an example code using Swing to create a dropdown list and to retrieve the selected value.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("下拉列表框示例");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String[] options = {"选项1", "选项2", "选项3"};
        JComboBox<String> comboBox = new JComboBox<>(options);
        
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedValue = (String) comboBox.getSelectedItem();
                System.out.println("选中的值是:" + selectedValue);
            }
        });

        frame.add(comboBox);
        frame.setVisible(true);
    }
}

In the example above, a dropdown menu with three options was created and an ActionListener was added to it to retrieve the selected value. When a user chooses an option, the ActionListener is triggered and will print the selected value to the console.

To create a drop-down list with JavaFX, you can use a ComboBox control and add an event listener to capture the selected value.

Leave a Reply 0

Your email address will not be published. Required fields are marked *