简体   繁体   中英

Update JTable after clicking a JButton

When i click the Button "Sale", the Table must show in the first row, which item i sold, and how much was it. But when i click a second time, it deletes de last row, and creates a new table. How can i create a new row, with the new Data? This is my code:

if (e.getSource()==sale)
    {
        int tempcod=0,tempcant=0; //tempcod is the code of the product,
       temocant is the number of products sold

    final DefaultTableModel model = new DefaultTableModel();

        model.addColumn("Product");
        model.addColumn("Price");

        try
        {
        tempcod=Integer.parseInt(cod.getText());
        tempcant=Integer.parseInt(quantity.getText());
        }
        catch(NumberFormatException a)
        {
            JOptionPane.showMessageDialog(null, "Invalid Number");
        }

        for (int j=0;j<nulo; j++) //nulo is the number of items at sale
        {

            if (tempcod==codigo[j]) //id the code i wrote exist in 
                                      the list of products
            {
                for (int k=0; k<nulo; k++)
                {
                    if (tempcod==ventaActual[0][k])
                    {
                        ventaActual[1][k]+=tempcant;
                    }
                    else
                    {
                    ventaActual[0][k]=tempcod;
                    ventaActual[1][k]=tempcant;
                    }
                }

                model.insertRow(model.getRowCount(), new Object[]{item[j],price[j]*tempcant});//this line creates the row of the table.
          //item[] is the name of the item, price[] is the price of the item
                JTable Lista= new JTable(model);
                lista1=new JScrollPane(Lista);
                lista1.setBounds(170,150,200,200);
                lista1.setEnabled(false);
                lista1.setVisible(true);
                this.add(lista1);

                a+=(tempcant*precio[j]);
                String b=Integer.toString(a);
                tot.setText(b);
                ventaInforme=ventaActual;
            }
            else
            {
                cod.setText(null);
                cantidad_n.setText(null);
            }
        }
    }

Your call to model.insertRow should insert a row into the table and fire the necessary events for the table to update itself. However, you need to get the existing model from the existing table, and then update that model.

eg DefaultTableModel model = (DefaultTableModel)myTable.getModel();

You should probably also get rid of the code that creates and adds a new table to your container, unless that's what you want.

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