Updating JTable on button click

后端 未结 1 1441
长发绾君心
长发绾君心 2021-01-23 01:18

I am working with a JTable with a Custom Table Model found here. I have updated my code with the suggestions provided in that post and have run into a new problem.

1条回答
  •  攒了一身酷
    2021-01-23 01:46

    I have searched on stackoverflow and a couple of people have said to use that method.

    No, you should not call any fireTableXxx methods outside of the context of the TableModel itself, people suggesting otherwise are simply wrong and it will cause you issues in the future. From the looks of your code, nothing has changed. If you've updated the TableModel according to the answer provided in your previous question, then there is no relationship with the data in the model to the external source. You need to manually reload the data from the external source, create a new TableModel and apply it to the table

    For example...

    JButton btnRefreshAllPlayers = new JButton("Refresh");
    
    btnRefreshAllPlayers.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent arg0) {
    
            TableModel model = new PlayerTableModel(FileHandler.getCompletedPlayers());
            table.setModel(model);
    
        }
    
    });
    

    I have also tried setting a new model with the updated ArrayList and it worked but did not keep the table row widths I previously set.

    This is a reasonable thing for the table to do, because it has no idea if the new model has the same properties/columns as the old, so it resets them.

    You could walk the ColumnModel, storing the column widths in a List or Map before you apply the model and reapply the widths

    Is there a proper way to update the JTable?

    You could provide your TableModel with a refresh method, which could load the data itself and trigger a tableDataChanged event

    public class PlayerTableModel extends AbstractTableModel {
        private final List summaries;
    
        public PlayerTableModel(List summaries) {
            this.summaries = new ArrayList(summaries);
        }
        // Other TabelModel methods...
    
        public void refresh() {
            summaries = new ArrayList<>(FileHandler.getCompletedPlayers());
            fireTableDataChanged();
        }
    }
    

    Then you would need to call this method in your ActionListener...

    PlayerTableModel model = (PlayerTableModel)table.getMode();
    model.refresh();
    

    0 讨论(0)
提交回复
热议问题