简体   繁体   中英

How to add multiple rows to JTable?

I'm trying to populate a JTable from a database, but the output is still empty. 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 :

| idp | codep | nomp | prix | stock |

"Quantité" in

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? and the Internet itself, all examples uses following line:

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

so you have to replace the code line ' DefaultTableModel model = new DefaultTableModel(); ' by DefaultTableModel model = (DefaultTableModel) table.getModel(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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