[英]How do I create an update button using JComboBox dropdown list in netbeans 8.2?
我想为下拉列表创建一个更新按钮,以从netbeans中的数据库获取数据。 在下面尝试了此方法,但无法使其正常工作。 有什么建议么? 非常感谢。
public class ViewProduct extends javax.swing.JFrame {
ResultSet rs;
PreparedStatement pst;
Connection conn;
final void FillList(){
try{
//establish connection to table
String url = "jdbc:derby://localhost:1527/ProductInformation";
String username = "admin1";
String password = "admin1";
Connection conn = DriverManager.getConnection(url,username,password);
Statement stat = conn.createStatement();
// get data from table in sql database
String Query = "SELECT * FROM VIEWPRODUCT";
ResultSet rs = stat.executeQuery(Query);
//
DefaultListModel DLM = new DefaultListModel();
while(rs.next()){
JList list = new JList();
JComboBox ProductID_dropdown = new JComboBox();
DefaultComboBoxModel listModel = new DefaultComboBoxModel();
list.setModel(listModel);
ProductID_dropdown.setModel(listModel);
}
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.toString());
}
您的代码中有些不正确或缺少的东西。 例如,您没有GUI。
而且由于我不知道您的项目或数据库的确切结构,我不得不即兴创作,并为您提供一种伪代码方法。 您将不得不更改和配置我在此处显示的几项内容。
首先,在您的方法之外创建一个JComboBox并将其添加到JPanel之类的容器中:
JPanel pane = new JPanel();
JComboBox productID_dropdown = new JComboBox();
JButton btn_updateViewProducts = new JButton("Update Results");
在此处添加了用于更新结果的按钮,其中包含一个ActionListener
,当有人单击该按钮时可以“监听”。 通常,您需要检索一个ResultSet
并将其内容放入变量中,如以下示例所示 :
// ActionListener for the button
btn_updateViewProducts.add(new ActionListener{
@Override
// When the button is clicked...
public void actionPerformed(ActionEvent arg0) {
// ... get the results out of your database (here it's an example database!
// Configure for your own one)
ResultSet rs = stat.executeQuery(Query);
while(rs.next()){
// "de-construct" every result of the ResultList into variables
String query = "select COF_NAME, SUP_ID, PRICE, " + "SALES, TOTAL " + "from " + dbName + ".COFFEES";
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
// Put items into JComboBox
productID_dropdown.addItem(coffeeName);
}
}
});
// Add the now filled JComboBox to the pane
pane.add(productID_dropdown);
您应该考虑的其他问题:
FillList
是最终的,这似乎很不正常,这背后的原因是什么? final
在方法中意味着它不能被子类覆盖,这在这里需要吗? FillList
是一种方法,由于编码约定,应该在开头写一个小写字母, ProductID_dropdown
(编码约定)也是如此 rs
类的短变量作为ResultSet
是完全可以的,但是,如果您的项目变大,则很难记住所有这些变量。 更好:让他们告诉你他们是什么。 代替rs
> resultSetViewProduct
或类似的东西。 PreparedStatement pst
我希望这有帮助。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.