Saturday, 28 February 2015

Add values to JComboBox in Java

Structure of the Problem Requirements 

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 listen 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() );
secondCB.setModel( new DefaultComboBoxModel( (String[])obj ) );

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

Output of the Program

Add values to JComboBox in Java

Add values to JComboBox in Java

Share it Please

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.


Post a Comment