Java JComboBox Get Selected Item Value

In this section we will discuss about how to get the selected item value form JComboBox.

Java JComboBox Get Selected Item Value

In this section we will discuss about how to get the selected item value form JComboBox.

Java JComboBox Get Selected Item Value

Java JComboBox Get Selected Item Value

In this section we will discuss about how to get the selected item value form JComboBox.

javax.swing.JComboBox provides the feature to choose one of several choices from the drop down list. In this tutorial we are discussing about how to store the selected item value of JComboBox into the database table. To store the selected item value of JComboBox in database we will use here MS Access. Before discussing about storing of data to the database table first, we will discuss about how to create a database table in MS Access.

To create a new database in MS Access we will be required to follow some following steps :

  • How to create MS Access Database
    • Run MS access -> Select Radio button Blank Access database

      Then press Ok. After click on OK button a dialog box will be opened for saving your database. You can specify the directory and give the database name with the extension '.mdb' as I give the database name 'swing.mdb in this tutorial. And then click on Create button (at Right corner of dialog box).

      When you will clicked on Create button a database will be created on your specified directory.

      Now you can create table in the database. When you will clicked on create button a dialog box will be opened to you for creating table.

       In a simple way you can create the table by double clicking on 'Create table in design view'. After double clicking on 'Create table in Design view' you can create a table. Give the field's name and their data type in the corresponding columns and to save the table try to close the open window it will ask you for saving the table then click on yes and give the name of table as below

      Click on OK button. Your table with the specified name will be created successfully. And you can see and work with your table as below :

  • How to create DSN in MS Access Database

      Creation of DSN is required because to use the JDBC-ODBC bridge driver. DSN(Data Source Name) specifies the connection between ODBC and a specific server. To create DSN following steps are required :

      In the first step you would be required to open the Control Panel -> Administrative Tools -> Data Sources (ODBC).

      After click on Data Source (ODBC) shortcut a dialog box will be opened to you. Go to tab System DSN.

      Click on Add button and select the Microsoft Access Driver (*.mdb) and click on Finish button

      After clicking on Finish a dialog box will open for providing the Data Source Name, give the DSN name and click on Select button

      When you will click on select button then a dialog box will be open for selecting your database. Go to your directory where you have saved your database at the time of its creation and select your database as below :

      Then Click on OK, after clicking on OK control will be return to the previous dialog box with the directory of your database as follows :

      Then click on OK, your DSN will be created with the given DSN name as follows :

      And then finally click on OK button. The process of DSN creation will be completed.

      0

Example

Here I am giving a simple example into which I shall get the combo box selected item value and stored it into the ms access database table. In this example I have created a table in the MS Access database and then written a Java swing program where added a combo box, using JComboBox, inside a frame. Also write the code for storing the data to the database table.

Source Code

1

GetValueOfJcomboBox.java

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class GetValueOfJcomboBox implements ActionListener{
	
	String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
	String petName ="";

private void createUI()
    {
        JFrame frame = new JFrame("JDBC All in One");
        JComboBox petList = new JComboBox(petStrings);
        petList.setPreferredSize(new Dimension(10,20));
        petList.setSelectedIndex(0);
        petList.addActionListener(this);
	    Container cn = frame.getContentPane();
	    JPanel p= new JPanel();	    	    
	    p.add(petList);
	    cn.add(p);
	    Insets insets = cn.getInsets();
	    Dimension size = p.getPreferredSize();
	    p.setBounds(80 + insets.left, 135 + insets.top,
	            size.width, size.height);
		cn.setLayout(new BoxLayout(cn,BoxLayout.Y_AXIS));
		frame.add(petList);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}

@Override
public void actionPerformed(ActionEvent e)
{
	JComboBox cb = (JComboBox)e.getSource();
    petName = (String)cb.getSelectedItem();
	for(String s : petStrings)
	{
		if(petName.equals(s))
		{
			addOperation();
			System.out.println("Value added successfully");
		}		
	  }
	}

 private void addOperation()
 {
	try
	{
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		Connection con = DriverManager.getConnection("jdbc:odbc:swing");
		String sql = "INSERT INTO PetTable(petName) Values('"+petName+"')";
		Statement st = con.createStatement();
		st.execute(sql);
		JOptionPane.showMessageDialog(null, "Record Added Succesfully.","Record Added",
				JOptionPane.INFORMATION_MESSAGE);
	}
	catch(Exception e)
	{
		JOptionPane.showMessageDialog(null, e.getMessage(),"Error",
				JOptionPane.ERROR_MESSAGE);
	}
  }
 public static void main(String args[])
 {
	 GetValueOfJcomboBox gvb = new GetValueOfJcomboBox();
	 gvb.createUI();
 }
}// class closed

Output

When you will execute the above example you will get the output as follows :

2

1. A frame will be opened which will contain the combo box.

2. When you will click on the arrow button showing at the frame added combo box a list will be displayed as follows :

3

3. When you will select any of the list item it will show in the combo box and that value will also be saved in the database table. After adding a data successfully a dialog box will be open. In the displayed list I have selected the Rabbit then the output will be as follows :

4

4. As well as a message 'Value added successfully' will also be displayed on console.

5. After completing this process when you will see the database table the selected item value will be added to the table as follows :

5

Download Source Code

Video of the Tutorial