📜  Java Swing-JComboBox(1)

📅  最后修改于: 2023-12-03 14:42:16.686000             🧑  作者: Mango

Java Swing-JComboBox

JComboBox is an important component in Java Swing which is used to create a drop-down list of items. It is a part of javax.swing package.

Syntax
JComboBox comboBox = new JComboBox();
Creating a Simple JComboBox

To create a simple JComboBox, we need to follow the below steps:

  1. Create an instance of JComboBox
  2. Add the items to the JComboBox
  3. Add the JComboBox to the JFrame
import javax.swing.*;

public class SimpleComboBoxExample {
    JFrame frame;
    JComboBox comboBox;

    SimpleComboBoxExample() {
        frame = new JFrame("Simple JComboBox Example");

        String[] items = {"Item 1", "Item 2", "Item 3", "Item 4"};
        comboBox = new JComboBox(items);

        frame.add(comboBox);
        frame.setSize(300, 300);
        frame.setLayout(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new SimpleComboBoxExample();
    }
}

The above code creates a simple JComboBox with 4 items and adds it to the frame.

Listening to Item Selections in JComboBox

To listen to item selections in JComboBox, we need to add an ActionListener to JComboBox.

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

public class ItemListenerExample implements ActionListener {
    JFrame frame;
    JComboBox comboBox;

    ItemListenerExample() {
        frame = new JFrame("JComboBox Item Listener Example");

        String[] items = {"Red", "Green", "Blue"};
        comboBox = new JComboBox(items);
        comboBox.addActionListener(this);

        frame.add(comboBox);
        frame.setSize(300, 300);
        frame.setLayout(null);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String selected = comboBox.getSelectedItem().toString();
        JOptionPane.showMessageDialog(frame, "Selected Item: " + selected);
    }

    public static void main(String[] args) {
        new ItemListenerExample();
    }
}

The above code creates a JComboBox with 3 items and adds an ActionListener to it. When the user selects an item, a message dialog box is displayed with the selected item's text.

Conclusion

JComboBox is a powerful component in Java Swing that helps to create drop-down lists of items. In this article, we discussed how to create a simple JComboBox and how to listen to item selections in it.