Arraylist在jtable显示中加倍

时间:2016-08-22 14:31:20

标签: java arrays jtable

java新手。 所以,这是我的代码。每当我点击添加按钮时,它也会添加我添加的先前数据。

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);
        }

2 个答案:

答案 0 :(得分:1)

两种解决方案,

首先解决方案,只需添加要添加到模型中的对象:

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() } );

第二个解决方案,从模型中删除所有表,然后通过for循环:

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);
    }

答案 1 :(得分:0)

在行coffeeArray.add(coff);中添加新咖啡(严重的小写类名?)后,循环所有数组coffeeArray并将每个咖啡元素添加到表中。 您每次都要添加所有数组,所以第一次添加第一个元素时,第二次添加第一个和第二个,第三次添加第一个,第二个和第三个,依此类推向前。 考虑只向表中添加新咖啡,而不是整个数组:

coffeeArray.add(coff); 
Object[] rowCoffee = {coff.getName(),coff.getCoffeeName(),coff.getPrice(),coff.isOrderMode(),coff.getQuanOrder()};
model.addRow(rowCoffee);