Using JComboBox

Guest Posts Steven



In this article I'm going to show you how to use JComboBoxes, this is a component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.

JComboBox, which lets the user choose one of several choices, can have two very different forms. The default form is the uneditable combo box, which features a button and a drop-down list of values. The second form, called the editable combo box, features a text field with a small button abutting it.

Here's an example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JLabel;

public class exampleJFrame extends JFrame implements ActionListener{

    private static final long serialVersionUID = 1L;
    private JPanel _panel;
    private String[] _options={"Option 1","Option 2","Option 3","Option 4"};// options for the combobox
    private JComboBox comboBox;
    private JLabel label;
    /**
     * Create the frame.
     */
    public exampleJFrame() {
        setVisible(true); //we make the window visible
        setResizable(false); // if write false, you won't be able to resize the window
        setTitle("Example"); //you set the title for the window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // you make the window appear at the center of the screen
        setSize(266,274); // you set the size of the window
        _panel = new JPanel();
        getContentPane().add(_panel);
        _panel.setLayout(null);

        comboBox = new JComboBox(_options);// you add the options to the combobox
        comboBox.setBounds(10, 11, 82, 20);
        comboBox.setEditable(false); // you can't edit it
        comboBox.addActionListener(this);
        _panel.add(comboBox);

        label= new JLabel("");
        label.setBounds(118, 60, 87, 14);
        _panel.add(label);

        update(getGraphics());
    }

    public void actionPerformed(ActionEvent e) {
        comboBox=(JComboBox)e.getSource();
        String option=(String) comboBox.getSelectedItem();
        changeLabel(option);
    }

    private void changeLabel(String pOption) {
        label.setText(pOption);
    }

    public static void main(String[] args) {
        exampleJFrame example=new exampleJFrame();
    }
}


Here's the result:

You select the option you want:

frame1

You click on it:

frame2