I am unable to populate a JComboBox
with database data. This is my code to fill combobox with database data. I am able to connect to the database. The catch block is there to display error messages. What happened was that the error message does not pop up and when my application runs, the combobox is empty. This is my database table, and I want to populate the names into the combobox.
package testing;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
public class combobox extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private static JComboBox combobox_database;
static Connection conn = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
sqliteconnection.dbConnector();
fillcombobox();
combobox frame = new combobox();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public combobox() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 619, 524);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JComboBox combobox_database = new JComboBox();
combobox_database.setBounds(208, 87, 175, 22);
contentPane.add(combobox_database);
}
public static void fillcombobox(){
try{
String sql = "SELECT name FROM testing_table";
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String s = rs.getString(2);
combobox_database.addItem(s);
}
pst.close();
rs.close();
conn.close();
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}