Add values to JComboBox in Java

The Program is about JComboBox in Java. JComboBox get text from drop menu and show the result against the value.This Program update the value of second JComboBox if we change first ComboBox. This JComboBox example checked the selected item and show the related data types.

Source Code 

package updateComboBox;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class CBNew extends JPanel implements ActionListener
{
    /**
  * Uzair
  */
 private static final long serialVersionUID = 1L;
 private JComboBox<String> firstCB;
    private JComboBox<String> secondCB;
    private Hashtable<String, String[]> hTable = new Hashtable<String, String[]>();

    public CBNew()
    {
        String[] i = { "Select Item", "Numbers", "Albhabets", "Special Characters" };
        firstCB = new JComboBox<String>( i );
        firstCB.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        firstCB.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        add( firstCB );

        //  Create sub combo box with multiple models

        secondCB = new JComboBox<String>();
        secondCB.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXX"); // JDK1.4 else coment this line
        add( secondCB );

        String[] s1 = { "Select Number", "One", "Two", "Three" };
        hTable.put(i[1], s1);

        String[] s2 = { "Select Albhabet", "A", "B", "C" };
        hTable.put(i[2], s2);

        String[] s3 = { "Select Special Characters", "- ! -", "- ? -", " @ " };
        hTable.put(i[3], s3);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)firstCB.getSelectedItem();
        Object obj = hTable.get( item );

        if (obj == null)
        {
            secondCB.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            secondCB.setModel( new DefaultComboBoxModel( (String[])obj ) );
        }
    }

    public static void main(String[] args)
    {
     JFrame frame = new JFrame("Test ComboBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new CBNew() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }
}

Output of the Program

Add values to JComboBox in Java

Add values to JComboBox in Java


Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment