How to create a dropdown list in Java?

To create a dropdown list box (also known as a dropdown menu) in Java, you can use the JComboBox class from the Swing components. Here is a simple example to demonstrate how to create a dropdown list box:

import javax.swing.*;

public class JComboBoxExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("JComboBox Example");

        String[] data = {"Option 1", "Option 2", "Option 3", "Option 4", "Option 5"};
        JComboBox<String> comboBox = new JComboBox<>(data);
        comboBox.setBounds(50, 50, 150, 30);

        frame.add(comboBox);

        frame.setSize(300, 200);
        frame.setLayout(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

In this example, we first import the JComboBox class, then create an instance of JFrame. We define a String array containing 5 options, and use the constructor of the JComboBox class to create a drop-down list. Finally, we add the drop-down list to the frame and display it by setting the frame’s size, layout, and visibility.

You can also add a listener to the drop-down list box to respond to user selections. Please refer to more documentation on the JComboBox class in Java Swing for additional functionality and options.

广告
Closing in 10 seconds
bannerAds