简体   繁体   中英

Java fireTableDataChanged() not updating JTable

fireTableDataChanged doesn't seem to work for me:

class Main:

    tblBookOfMonth = new JTable(tableModel);

    tableModel.setData();
    tableModel.fireTableDataChanged();
    tblBookOfMonth.repaint();

    frame.add(tblBookOfMonth, BorderLayout.CENTER);
    frame.add(pnlNorth, BorderLayout.NORTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

class MySQLTableModel:

public class MySQLTableModel extends AbstractTableModel{

private Object[][] data;
boolean bool = false;


public MySQLTableModel(Object[][] data) {
    this.data = data;
}

public MySQLTableModel() {
    this.data = new Object[0][0];
}

public void setData() {
    bool = true;
}

@Override
public int getColumnCount() {
    if(bool) {
        return 4;
    }
    return 0;
}

@Override
public int getRowCount() {
    if(bool) {
        return 4;
    }
        return 0;
}

@Override
public Object getValueAt(int arg0, int arg1) {
    return "test";
}

I deleted half of my code and replaced it with test code to minimize possible error sources, but I still can't figure out what's wrong.

Table should show me a 4x4 grid saying 'test'. When I delete the if-clause and always return 4, it works as it should.

fireTableDataChanged doesn't seem to work for me:

What does that mean? We are not mind readers. What happens and what do you expect to happen?

As already mentioned the fireXXX(() methods should be invoked from the TableModel itself, not the application code. That is the TableModel is responsible for invoking those methods to let the table know that changes have been made. So any code should be invoked from within the setData() method.

From a quick look at the code it looks like you are trying to change the number of columns that are displayed. If so then I suspect you should be adding the following code to the setData() method:

 fireTableStrucutreChanged();

This will tell the table to create a TableColum for each column in the TableModel so the table can display the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM