我正在尝试从数据库中选择项目的名称,然后将其保存到数组中以便稍后将其添加到JComboBox中,但由于某种原因,它根本不会从数据库中获取它。
以下是应该执行此操作的代码部分:
public BirthdayForm()
{
super("Birthday Party Supplies Rental Form");
String url = "jdbc:mysql://localhost/";
String dbName = "partySupplies";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String pw = "";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,username,pw);
setLayout(new FlowLayout());
String[] list = null;
chooseItem = new JLabel("Choose Item:");
String selectSQL = "SELECT productName FROM birthday where productName = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
String name = rs.getString(2);
System.out.println(name);
for(int i=0; i<8; i++){
list[i] = name;
}
}
items = new JComboBox(list);
chooseQuantity = new JLabel("Choose Quantity:");
quantity = new JTextField("1");
choose = new JPanel();
choose.setLayout(new GridLayout(1,4));
choose.add(chooseItem);
choose.add(items);
choose.add(chooseQuantity);
choose.add(quantity);
add(choose);
//other codes
答案 0 :(得分:1)
您必须从数据库中选择它。
combobox.addItem(rs.getString("items"));
需要&#34;项目&#34;从你的结果集中,它将它放入一个字符串中,然后将它添加到你的组合框中。
答案 1 :(得分:0)
您可以将字符串添加到JComboBox,如下所示:
String item1 = "This is my first item";
String item2 = "This is my second item";
combo.addItem(item1);
combo.addItem(item2);
最后它看起来像这样: