Home Java Example Java Swing Combo box In Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Combo box In Java

Advertisement
In this section, you will learn about the JComboBox Component of swing in java.

Combo box In Java

This tutorial will help you to create a Combo box in java. Combo box allow you to select one of the option which appear at the user request. It is possible that combo box can be editable by which a user can type a value in the editable field. Combo box can be created using JCombobox in java which  is sub classed to JComponent. It provides you options to select an item from the item list. You can never select more than one item from a combo box. Combo Box can be either editable or  non-editable means only readable.

Constructor of JCombobox are as follows:

  • JComboBox() : Create a combo box with a default.
  • JCombobox(ComboBoxModel a) : Create a combo box that accept item from the existing combo box mode.
  • JComboBox(Object[]  ob) : Create a combo box that contain the element in the array.
  • JComboBox(Vector <?>  v) : Create a vector that contain the element in vector.

And, some of the method of JComboBox are actionPerformed(ActionEvent e) which is implemented as public,  addItem(Object a) which add an item to the item list, addItemListener(ItemListener listener) which adds an ItemListener, getAction() which returns the currently set action for this ActionEvent Source, getActionCommand() which return the action command included in the event. Now, with the help of the example we are going to create.

Example : Combo Box in Java

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

public class Combobox {
	JComboBox combo;
	JTextField txt;

	public static void main(String[] args) {
		Combobox b = new Combobox();
	}

	public Combobox() {
		String country[] = { "India", "Australia", "Canada", "Boston" };
		JFrame frame = new JFrame("JComboBox Example");
		JPanel panel = new JPanel();
		combo = new JComboBox(country);
		combo.setBackground(Color.white);
		combo.setForeground(Color.black);
		txt = new JTextField(10);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 300);
		frame.setVisible(true);
		panel.add(combo);
		panel.add(txt);
		frame.add(panel);
		combo.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				String str = (String) combo.getSelectedItem();
				txt.setText(str);
			}
		});

	}
}

Output from the program:

Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 6, 2013

Ask Questions?    Discuss: Combo box In Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com