Monday , December 11 2017
Home / java / Java JComboBox Editable Example

Java JComboBox Editable Example

In this tutorials, I am going to show you how to use Java JComboBox. Java ComboBox is a swing component that combines drop down with editable field.

Java JComboBox :


package com.onlinetutorialspoint.swing;

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.activation.MailcapCommandMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class JComboBoxDemo extends JFrame {

    private JComboBox comboBox;
    private JLabel label;
    private static final String[] names = {
            "bulb1",
            "bulb2",
            "bulb3"};

    private Icon[] icons = {
            new ImageIcon("C:\\images\\bulb1.gif"),
            new ImageIcon("C:\\images\\bulb2.gif"),
            new ImageIcon("C:\\images\\bulb3.gif") };

    JComboBoxDemo() {
        super("JCombobox Demo");

        setLayout(new FlowLayout());
        comboBox = new JComboBox(names);
        comboBox.setMaximumRowCount(3);

        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    label.setIcon(icons[comboBox.getSelectedIndex()]);
                }
            }
        });
        add(comboBox);
        label = new JLabel(icons[0]);
        add(label);
        
    }

    public static void main(String[] args) {
        JComboBoxDemo jComboBoxDemo = new JComboBoxDemo();
        jComboBoxDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jComboBoxDemo.setSize(350, 150);
        jComboBoxDemo.setVisible(true);
    }

}

Output :

Java JComboBox

Changing the Items :

Java JComboBox 1

Editable JComboBox :

We can make the JComboBox as editable by using setEditable(true) like below.


comboBox.setEditable(true);

Output :

Java JComboBox Editable

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java Graphics2D Class Example

In this tutorials, we are going to see how to use Java Graphics2D class. Java …

Leave a Reply

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