我无法使用数据库数据填充JComboBox
。这是我用数据库数据填充组合框的代码。我能够连接到数据库。 catch块用于显示错误消息。发生了什么是错误消息没有弹出,当我的应用程序运行时,组合框是空的。这是我的数据库表,我想将名称填充到组合框中。
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);
}
}
}
答案 0 :(得分:2)
您的查询会选择一个属性name
,因此传递给getString()
的相关columnIndex
应为1
。
while(rs.next()) {
String s = rs.getString(1);
combobox_database.addItem(s);
}
如上所述here,您还可以使用columnLabel
;显示了一个完整的示例here;这个相关的example使用JPA。
答案 1 :(得分:1)
我看到的是" JComboBox combobox_database"在另一个方法中定义和初始化,因此方法fillcombobox()没有引用它。我打赌你的程序有一些编译错误。