user2351151
user2351151

Reputation: 733

JTable reload data

I have the following JTable in code:

String[] columnNames = {"Name", "Category", "Seller", "Sell Price", "Current Bid", "End Date", "Open"};
Object[][] data = GetAuctionTableData();
final JTable AuctionTable = new JTable(data, columnNames); 

I also have a Button on the form and wish to reload the data into the table on the click of the button. How do I do this? Do I need to use a AbstractTableModel?

EDIT

Here is the code for the button:

    RefreshAuctionButton.addActionListener(new ActionListener() {  
    public void actionPerformed(ActionEvent e)
    {
        Object[][] data = GetAuctionTableData();
        AuctionTable = new JTable(data, columnNames);
    }});

This code does not work as the JTable is declared as final. I currently have it as final because it is accessed from inner classes (buttons, as above).

Upvotes: 1

Views: 3018

Answers (2)

Ariel D. Moya Sequeira
Ariel D. Moya Sequeira

Reputation: 492

It depends on what you want the button to change about the table.

  • If the button just triggers updates in the objects within data, then you only need to use AuctionTable.update (or something like that).

  • If it triggers an insertion, then it would be useful to add just the row to be inserted directly to AuctionTable. Use ((DefaultTableModel) AuctionTable.getModel).addRow(...);

  • If it triggers a deletion, then you would need just the index of the row to be deleted. Use ((DefaultTableModel) AuctionTable.getModel).removeRow(...);

Otherwise, I'll need more information about the button's action, or you can make a call to GetAuctionTableData() each time the button is pressed to reload the whole JTable's information (something that might not be desirable at all).

EDIT

To reload the whole contents while keeping the final modifier for AuctionTable, use the setDataVector method instead of re-setting the table in the button's action listener.

RefreshAuctionButton.addActionListener(new ActionListener() {  
    public void actionPerformed(ActionEvent e)
    {
        Object[][] data = GetAuctionTableData();
        ((DefaultTableModel) AuctionTable.getModel()).setDataVector(data, columnNames);
    }
});

You'll have to set your columnNames to final as well, though.

Upvotes: 1

Sanjaya Liyanage
Sanjaya Liyanage

Reputation: 4746

Use a DefaultTableModel and use addRow(Object[] rowData) to set the data.You can notify the data changes by model.fireTableDataChanged();

Upvotes: 0

Related Questions