Question

I have created a DefaultTableModel that is showing a very basic user league table in a JTabbedPane.

I want to add a row using some data I collect from a different class. This code will not run but here is a sample:

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Statistics extends JPanel {
    public Object[][] data;

public Statistics() {
    super(new GridLayout(1,0));
    String[] columnNames = {"Name", "Games Played", "Games Won"};
    Object[][] data = {
            {"Tom", new Integer(5), new Integer(2)},
            {"Steve", new Integer(2), new Integer(0)},
    };
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    JTable table = new JTable(model);
    table.setFillsViewportHeight(true);
    table.setVisible(true);
    table.setEnabled(false);

    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
}


}

then I call this from my main class:

...
stats = new JPanel(); //create a new JPanel for table to go on
...
tp.addTab ("Statistics", stats); // add panel to JTabbedPane
..
leagueTable = new Statistics();// add the table to the stats panel
       stats.add(leagueTable);

this is showing up and its fine, but can anyone guide me as to what syntax I use to add a row, I have tried:

 leagueTable.addRow(table.getRowCount(), new Object[]{"ange", 5, 3});

but this does not work, eclipse asks me to add a method called 'addRow' to Statistics class, but I thought 'addRow' was already a method of DefaultTableModel, so I am very confused. Can anyone help me out on how to add a row of data to the table? Thanks IA

Was it helpful?

Solution

addRow is a method of the TableModel but you're invoking the method on the Statistics class. You could create a new method to add the data:

public class Statistics extends JPanel {
    private DefaultTableModel model

    public Statistics() {
       super(new GridLayout(1,0));
       model = new DefaultTableModel(data, columnNames);
       ...
    }

    public void addData(Object[] data) {
       model.addRow(data);
    }
}

Side note: Typically you don't want to extend JPanel here if not adding new functionality so a redesign is probably in order

OTHER TIPS

leagueTable is an instance of your Statistics class. So it doesn't have an addRow() method.

Possible solution:

  • Make your DefaultTableModel a variable in your Statistics class.
  • Create a method in Statistics that interacts with the table model by calling addRow() on the model.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top