简体   繁体   English

如何向JTable添加多行?

[英]How to add multiple rows to JTable?

I'm trying to populate a JTable from a database, but the output is still empty. 我正在尝试从数据库填充JTable,但是输出仍然为空。 Here is my code : 这是我的代码:

    private void buttonsearchActionPerformed(java.awt.event.ActionEvent evt)
    {
        conn = DatabaseConnection.dbConnection();
        try {
            String Sql="select idp,nomp,prix,stock from produit where codep='" 
                       + textsearch.getText() + "'";
            pst = conn.prepareStatement(Sql);

            ResultSet rs = pst.executeQuery();
            DefaultTableModel model = new DefaultTableModel();
            Object[] columns = {"Id Produit", "Nom Produit", "Quantité", "Prix", "Stock"};
            model.setColumnIdentifiers(columns);
            table.setModel(model);
            Object[] row = new Object[5];

            if (rs.next())
            {
                row[0] = rs.getInt("idp");
                row[1] = rs.getString("nomp");
                //row[2] = rs.getString("");
                row[3] = rs.getString("prix");
                row[4] = rs.getString("stock");
                model.addRow(row);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }                        

table "poduit" is : 表“ poduit”是:

| idp | codep | nomp | prix | stock |

"Quantité" in “Quantité”在

Object[] columns = {"Id Produit", "Nom Produit", "Quantité", "Prix", "Stock"}; 

It meant to modify numbers of items to create a billing. 这意味着修改项目数以创建开票。

my issue is the 2nd row is pasted right on the 1st one Thanks for help 我的问题是第二行粘贴在第一行上

According How to add row in JTable? 根据如何在JTable中添加行? and the Internet itself, all examples uses following line: 和Internet本身,所有示例都使用以下行:

DefaultTableModel deFaultTableModel = (DefaultTableModel) myJTable.getModel();

so you have to replace the code line ' DefaultTableModel model = new DefaultTableModel(); 因此,您必须替换代码行' DefaultTableModel model = new DefaultTableModel(); ' by DefaultTableModel model = (DefaultTableModel) table.getModel(); 'by DefaultTableModel model = (DefaultTableModel) table.getModel(); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM