-1

I created an object type arrayList but table still not identifying it as an object and giving error

this is the error it is producing.

no suitable method found for add (object[])

Below is the code is used:

ArrayList<Object> CartItems = new ArrayList<Object>();

cartCheckout.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Cartgui.setVisible(true);
        for (int i = 0; i < candyList.size(); i++) {
            String name = candyList.get(i).getCandyName();
            int weight = candyList.get(i).getweight();
            int priceLbs = candyList.get(i).getPriceLbs();
            Object[] data = {name, weight, priceLbs};

            Cartgui.add(data);//this line is producing error
        }
    }
});

I expect the output to see name,weight and pricelbs in tabular form in table. cartgui is the tablename

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Salman Ahmed
  • 50
  • 10

1 Answers1

0

The myTable.add(something) method doesn't do what you think. You wish you could do something more like myTable.getTableModel().addData(something), which is conceptually correct, though no such addData() method exists.

You may want to do something like

TableModel myModel = new DefaultTableModel(something);
JTable myTable = new JTable(myModel);

where there are several options for something because DefaultTableModel has several constructors.

However I personally almost never use DefaultTableModel. Instead I do something like

class MyTableModel extends AbstractTableModel {
    //override getRowCount(), getColumnCount(), getColumnName(), getValueAt(), and possibly isCellEditable() and setValueAt()
}

MyTableModel myModel = new MyTableModel(); // or pass parameters since you're writing the constructor(s)
JTable myTable = new JTable(myModel);

because in the end it's usually easier and more satisfying this way.

[edit: And if you want to call myModel.addData(something) from an ActionListener then you have to go the AbstractTableModel route, since DefaultTableModel doesn't have that functionality. Since MyTableModel is your class, you can write an addData() method for it.]

Btw, your variables CartItems and Cartgui violate standard Java coding conventions. They should start with lower-case letters. However this has no effect whatsoever on whether your code works or not.

bitguru
  • 21
  • 2