JComboBox in Java
To create a drop-down list (also known as a combo box) in Java Swing, you can use the JComboBox
class. Here's an example of how to create a basic drop-down list:
typescriptimport javax.swing.*;
public class MyFrame extends JFrame
{
public MyFrame()
{
String[] options = {"Option 1", "Option 2", "Option 3"};
JComboBox<String> comboBox = new JComboBox<>(options);
add(comboBox);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args)
{
new MyFrame();
}
}
In this example, we first create an array of strings that represent the options we want in our drop-down list. Then we create a JComboBox
object and pass in the array of options as a parameter. We add the JComboBox
to our JFrame
, call pack()
to set the size of the window based on its contents, and then set the default close operation, location, and visibility of the window.
You can customize the behavior and appearance of the JComboBox
by setting properties like the selected item, the number of visible rows, and the renderer that displays the items in the list. You can also add listeners to the JComboBox
to respond to user input.
Comments
Post a Comment