Hello,

I am new to java. I want to display the database records in JComboBox. I have 2 combo boxes. say color and object,whenever i'll select any color from combo box, next combo box should display the objects of that color. I have write one code for it, I use action listener for click on item of combo box. If I execute it first time, it goes prefrct, but
object combo gets duplicated, if I again click on any item in color combo.

I think query gets executed on every click. How can I overcome this?

Thanks In Advance

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

import javax.swing.*;

public class ComboBox {

	public static void main(String args[])
	{
		
		JFrame f = new JFrame();
		f.setLayout(null);
		JLabel label_1 = new JLabel("color");
		JLabel label_2 = new JLabel("object");
		
		final JComboBox combo_1 = new JComboBox();
		final JComboBox combo_2 = new JComboBox();
		
		JButton b1=new JButton("Search"); 
		
		
		label_1.setBounds(20,20,200,20);
		combo_1.setBounds(150,20,170,20);
		label_2.setBounds(20, 40,200, 60);
		combo_2.setBounds(150, 60, 170, 20);
		
		b1.setBounds(150,270,80,20); 
		
		f.add(label_1);
		f.add(label_2);
		f.add(combo_1);
		f.add(combo_2);
		f.add(b1);
		f.setVisible(true);
		f.setSize(400, 400);
		
		try{        

			
			
			Class.forName("com.mysql.jdbc.Driver");          
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbakh", "root", "root");           
				Statement st=con.createStatement();           
				ResultSet rs=st.executeQuery("select distinct color_1 from color ");           
				while(rs.next())
				{           
					combo_1.addItem(rs.getString("color_1"));           
				}   
				
		}catch (Exception e){}
				
		
		combo_1.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
			String color = combo_1.getSelectedItem().toString();
			//System.out.println(man);
			
			
			
			try{
				Class.forName("com.mysql.jdbc.Driver");          
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbakh", "root", "root");           
				Statement st=con.createStatement();  
				ResultSet r=st.executeQuery("select object_1 from object where color='"+color+"' ");
					while(r.next())
					{	
						combo_2.addItem(r.getString("object_1")); 
					}
				}
			catch (Exception a){}
			}
		});
		
		
	}
}

A comment on your code:
ALWAYS do something in a catch block to show you when there are errors.

object combo gets duplicated, if I again click

Where do you clear the combo box before adding the new items?

Edited 5 Years Ago by NormR1: n/a

This article has been dead for over six months. Start a new discussion instead.