Database values in JComboBox


 

Database values in JComboBox

In this section, you will learn how to display values in JComboBox from database.

In this section, you will learn how to display values in JComboBox from database.

Database values in JComboBox

In this section, you will learn how to display values in JComboBox from database. For this, we have allowed the user to enter any character as a key in the textbox .Based on this key value, the results from the database will get displayed on the ComboBox. If there will be  no data that matches the key value, the combobox will get disappeared.

Here is the code:

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

class ComboExample {
	ComboExample() {
		JFrame f = new JFrame();
		f.getContentPane().setLayout(null);
		final JComboBox combo = new JComboBox();
		final JTextField text = new JTextField();
		text.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
		        String ch = text.getText();
			combo.removeAllItems();
			if (ch.equals("")) {
			combo.setVisible(false);
			} else {
                        System.out.println(ch);
			try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection connect = DriverManager.getConnection(								"jdbc:mysql://localhost:3306/register", "root","root");
			Statement st = connect.createStatement();
			ResultSet rs = st
			.executeQuery("Select name from data where name like '"+ ch + "%'");
                        while (rs.next()) {
			String name = rs.getString("name");
			if (name.equals("")) {
			combo.addItem("");
			combo.setVisible(false);
			} else {
			combo.addItem(rs.getString("name"));
			System.out.println(rs.getString("name"));
			combo.setVisible(true);
			}
			}
			} catch (Exception ex) {
         		}
			}
	             	}

			public void keyTyped(KeyEvent e) {
			}

			public void keyPressed(KeyEvent e) {
			}
		});
		text.setBounds(20, 20, 150, 20);
		combo.setBounds(20, 50, 150, 20);
		f.add(text);
		f.add(combo);

		f.setSize(400, 200);
		f.setVisible(true);
		combo.setVisible(false);

	}

	public static void main(String[] args) {
		ComboExample c = new ComboExample();
	}
}

Output:

Ads