Home Java Example Java Swing Create a JComboBox Component in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Create a JComboBox Component in Java

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

Create a JComboBox Component in Java

     

In this section, you will learn about the JComboBox Component of swing in java. The JComboBox is used to display drop-down list. It provides you options to select an item from the item list. You can never select more than one items from a combo box. Combo Box can be whether editable or only non-editable means only readable.

This program displays a simple combo box on the frame which contains multiple items like: BCA, MCA, PPC etc. The background color of this combo box is gray and foreground color is red. Here, the background color of the combo box and the foreground color is set using the setBackground(Color) and setForeground(Color) method of the JComboBox class. When you select the item from the combo box then the selected item is displayed in the text box. Image of the result for the given program is as follows in the pictorial form:

Swing Combo Box Component

And
Swing Drop-Down List

APIs used in the program:

JComboBox:
This is the class which is used to create a combo box in swing using it's constructor.

itemStateChanged():
This is the method which receives the ItemEvent generated by the addItemListener() method of the JComboBox class. The event is generated when you select item from the combo box.

Here is the code of program:

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 course[] {"BCA","MCA","PPC","CIC"};
  JFrame frame = new JFrame("Creating a JComboBox Component");
  JPanel panel = new JPanel();
  combo = new JComboBox(course);
  combo.setBackground(Color.gray);
  combo.setForeground(Color.red);
  txt = new JTextField(10);
  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);
  }
  });
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(400,400);
  frame.setVisible(true);
  }
}

Download this example.

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: April 14, 2007

Ask Questions?    Discuss: Create a JComboBox Component in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
John
July 7, 2011
JComboBox

I am trying to create a JComboBox that has three options Yes,No and One months rent.If yes is selected then it will prompt the user to enter a amount.If no and one months rent is selected they go on to the next item. Thank you for your help. John
hiwa
November 11, 2011
JCombobox

hi please I want bay any index in combobox call one method e.x/ if i have combobox and have for index and in this combobox why i can call 4method by these 4index
Darshan Rahate
January 11, 2012
combobox in swing Java

if we type any character in combo box then we get list of related character of word in combo box no other character of word.
Obed
March 25, 2013
thumbs up rose

Good day..pliz help me to create the user inface that can view, add, delete, reset and update data in the sql server. The user should be able to select the id from the dropdow list and the data should be displyed on the combo with corresponding id. here is my code with the missing user interface. import java.awt.Font; import java.awt.GridLayout; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.swing.*; import java.awt.event.*; import java.sql.*; public class ProductInfo extends JFrame implements ActionListener { //code user interface here// try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con= DriverManager.getConnection("jdbc:odbc:LecoDB", "sa","niit@123"); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT EventID FROM Events"); while (rs.next()) { idCombo.addItem(Integer.toString(rs.getInt(1))); } con.close(); } catch(Exception e) { System.out.println ("error : "+e); } } @Override public void actionPerformed(ActionEvent ae) { if("Exit".equals(ae.getActionCommand())) System.exit(0); if("Delete".equals(ae.getActionCommand())) { try { con = DriverManager.getConnection("jdbc:odbc:LecoDB", "sa", "niit@123"); stat = con.prepareStatement ("DELETE from Event WHERE EventID = ?"); String selected_id = idCombo.getSelectedItem().toString(); int id = Integer.parseInt(selected_id); stat.setInt (1, id); stat.executeUpdate(); con.close(); idCombo.removeActionListener(this); con =DriverManager.getConnection("jdbc:odbc:LecoDB", "sa","niit@123"); stmt = con.createStatement(); rs = stmt.executeQuery ("SELECT p FROM Events"); idCombo.removeAllItems(); while (rs.next()) idCombo.addItem(Integer.toString(rs.getInt(1))); con.close(); idCombo.addActionListener(this); teventid.setText(""); teventname.setText(""); tstartdate.setText(""); tenddate.setText(""); tlocation.setText(""); tnoofpeople.setText(""); tstaffrequired.setText(""); error.setText("Row Deleted"); } catch (Exception e) { System.out.println ("Error" + e); error.setText("Row connot be Deleted"); } } if("insert".equals(ae.getActionCommand())) { try { con = DriverManager.getConnection("jdbc:odbc:LecoDB", "sa", "niit@123"); stat = con.prepareStatement("INSERT INTO Events VALUES(?, ?, ?, ?, ?, ?, ?)"); String id = teventid.getText(); String EventName= teventname.getText(); String StartDate = tstartdate.getText(); String EndDate = tenddate.getText(); String Location = tlocation.getText(); String NoOfPeople = tnoofpeople.getText(); String StaffRequired = tstaffrequired.getText(); stat.setInt(1, Integer.parseInt(id)); stat.setString(2, EventName); stat.setString(3, StartDate); stat.setString(4, EndDate); stat.setString(5, Location); stat.setString (6, NoOfPeople); stat.setString(7, StaffRequired); stat.executeUpdate(); con.close(); idCombo.removeActionListener(this); con=DriverManager.getConnection("jdbc:odbc:LecoDB", "sa", "niit@123"); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT EventID FROM Events"); idCombo.removeAllItems(); while (rs.next()) idCombo.addItem(Integer.toString(rs.getInt(1))); con.close(); idCombo.addActionListener(this); error.setText("Row Inserted"); } catch (Exception e) { System.out.println("Error1" +e); error.setText("Rows cannot be inserted"); } } if(ae.getSource() == idCombo) { try { con = DriverManager.getConnection("jdbc:odbc:LecoDB", "sa", "niit@123"); String selected_id = idCombo.getSelectedItem().toString(); int id = Integer.parseInt(selected_id); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT EventName, StartDate, EndDate, Location,NoOfPeople, StaffRequired FROM Events WHERE EventID =" +id); rs.next(); teventid.setText(selected_id); teventname.setText(rs.getString(1)); tstartdate.setText(rs.getString(2)); lenddate.setText (Integer.toString(rs.getInt(3))); tlocation.setText(rs.getString(4)); tnoofpeople.setText(rs.getString(5)); tstaffrequired.setText(rs.getString(6)); con.close(); } catch (Exception e) { System.out.println ("Error " +e); } } if("Update".equals(ae.getActionCommand())) { try { con = DriverManager.getConnection("jdbc:odbc:LecoDB", "sa", "niit@123"); stat = con.prepareStatement("UPDATE Events SET EventID =?, Location = ?, StartDate= ?, EndDate =?, NoOfPeople, StaffRequired where p_id = ?"); String EventName = teventname.getText(); String StartDate = tstartdate.getText(); String EndDate = tenddate.getText(); String Location= tlocation.getText(); String NoOfPeople= tnoofpeople.getText(); String StaffRequired= tstaffrequired.getText(); String id_selected = teventid.getText(); int id = Integer.parseInt(id_selected); stat.setString(1, EventName); stat.setDouble(2, Double.parseDouble(StartDate)); stat.setDouble(3, Double.parseDouble(EndDate)); stat.setString(4, Location); stat.setString(5, NoOfPeople); stat.setString(6, StaffRequired); stat.setInt(5, id); stat.executeUpdate(); con.close(); error.setText( "Row Updated"); } catch (Exception e) { System.out.println("Error " + e); error.setText("Cannot update the row"); } } if ("clear".equals(ae.getActionCommand())) { teventid.setText(""); teventname.setText(""); tstartdate.setText(""); tenddate.setText(""); tlocation.setText(""); tnoofpeople.setText(""); tstaffrequired.setText(""); } } public static void main (String args[]) { ProductInfo p; p =new ProductInfo(); frame.setSize (400, 550); frame.setVisible(true); } }
MOLLY
June 27, 2013
JAVA

output to de hi ni rkhi program ki,coding b glt h, ye kya bna rkha h. Program dhang k with correct coding upload kia kro.........
Plamen
June 24, 2013
:)

Very useful, thank you
venky cam
July 24, 2013
java

this language is very diffculty.
cam
July 24, 2013
java

this language vr deffrent
Rachel
December 17, 2011
jcombobox listener

how exactly would i go about writing a listener if i have a combo box with book genres and i want (depending on the genre selected), selected books of that genre to be shown in a JList (so that when the user selects one of the books, an image of the book is shown). so what listener do i use? action or item listener? and how to i write it? with "if" statements??
DMCA.com