WHAT'S NEW?

Loading Data in Combo Box from Database

Consider the following
Database Name: demodb
Table: Student (id int Primary Key, name varchar(100),percentage float)



Now let us consider a scenario where we need to load the names of Student in a Combo Box.

Basically i will write method by name loadName() which would like this.

public ArrayList<String> loadName()
{
ArrayList<String> list=new ArrayList<String>();
//Create a ArrayList to hold the list of names.
try
{
//Load the names from database table using JDBC.
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/demodb";
String user="root";
String password="your-db-password";
Connection con=DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
String query="Select name from student;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
list.add(rs.getString(1));
}
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// Return the list .
return list;
}


Now we have to integrate the above discussed method in a Swing form.

Now let us assume that combo is the object of JComboBox and this is how we will add the data in it.

             combo=new JComboBox();
     for(String name: loadName())
{
combo.addItem(name);
}
      combo.setBounds(100,100,200,30);
      c.add(combo);



So here is the full code for loading data in JComboBox.


LoadDataInCombo .java

iimport javax.swing.*;
import java.util.*;
import java.sql.*;
import java.awt.*;



public class LoadDataInCombo extends JFrame
{
JComboBox combo;
JLabel label;

LoadDataInCombo()
{
super("Load Data In Combo");
setSize(500,500);
  setResizable(false);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
       setLayout(null);
Container c=getContentPane();
c.setBackground(Color.WHITE);

combo=new JComboBox();
for(String name: loadName())
{
combo.addItem(name);
}
combo.setBounds(100,100,200,30);
c.add(combo);

setVisible(true);

}

public ArrayList<String> loadName()
{
ArrayList<String> list=new ArrayList<String>();
//Create a ArrayList to hold the list of names.
try
{
//Load the names from database table using JDBC.
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/demodb";
String user="root";
String password="your-db-password";
Connection con=DriverManager.getConnection(url,user,password);
Statement stmt=con.createStatement();
String query="Select name from student;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
list.add(rs.getString(1));
}
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// Return the list .
return list;
}

public static void main(String[] args)
{
LoadDataInCombo app=new LoadDataInCombo();
}


}

---------------------------------------Output would look like--------------------------------------------









0 comments:

Post a comment