Ji L Ji L - 3 months ago 23
Java Question

Arraylist doubled in jtable display

New to java.
So, here's my code. Whenever I click on add button, it will also add the previous data I added.

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {

DefaultTableModel model = (DefaultTableModel)table.getModel();

coffee coff = new coffee(name.getText(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue());

coffeeArray.add(coff);

for(int i = 0; i < coffeeArray.size(); i++)
{
String customerName = coffeeArray.get(i).getName();
String cofName = coffeeArray.get(i).getCoffeeName();
int price = coffeeArray.get(i).getuPrice();
String OrderMode= coffeeArray.get(i).isOrderMode();
int quantity = coffeeArray.get(i).getQuanOrder();

Object[] rowCoffee = {customerName,cofName,price,OrderMode,quantity};

model.addRow(rowCoffee);
}

Answer

Two solutions,

First solution, just add the object you are wanting to add to the model:

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {   

    DefaultTableModel model = (DefaultTableModel)table.getModel();

    coffee coff = new coffee(name.getText(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue());

    coffeeArray.add(coff);

    //Instead of going through the for loop, adding objects you already have, just add the one you just added to the model.

    model.addRow( new Object[] {coff.getName(), coff.getCoffeeName(), coff.getuPrice(), coff.isOrderMode(), coff.getQuanOrdered() } );

Second solution, remove all tables from the model, then go through the for loop:

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {   

    DefaultTableModel model = (DefaultTableModel)table.getModel();

    coffee coff = new coffee(name.getText(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue());

    coffeeArray.add(coff);

    //Remove all rows before adding everything from ArrayList.
    for(int i = 0; i < model.getRowCount(); i++)
        model.removeRow(i);

    for(int i = 0; i < coffeeArray.size(); i++)
    {
       String customerName = coffeeArray.get(i).getName();
       String cofName = coffeeArray.get(i).getCoffeeName();
       int price = coffeeArray.get(i).getuPrice();
       String OrderMode= coffeeArray.get(i).isOrderMode();
       int quantity = coffeeArray.get(i).getQuanOrder();

       Object[] rowCoffee = {customerName,cofName,price,OrderMode,quantity};

       model.addRow(rowCoffee);
    }
Comments