简体   繁体   中英

How to change value of a cell in a table model in Java?

I created a class inheriting from AbstractTableModel. I want to override setValueAt(), so that it will change the value of the cell in row r and column c into the multidimensional array v . But I keep getting errors.

public class ItemListTableModel extends AbstractTableModel{

public void setValueAt(Object v, int r, int c) {  
    rowData[r][c] = v;// This is where the error is.
    fireTableCellUpdated(r, c);  
}  

@Override
public int getRowCount() {

}

@Override
public int getColumnCount() {

}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {

}

public boolean isCellEditable(int row, int col){ 
    return true; 
}  

}

AbstractTableModel has no concept of the content of the model or how it's managed, that's kind of the point. It's designed to allow developers to design their own models based on their own complex requirements.

A simpler solution would be to use a DefaultTableModel , which provides all the functionality out of the box...

DefaultTableModel model = new DefaultTableModel(rows, columns); // you need to define rows and columns for yourself
model.setValueAt(row, column, value); // Again, you need to define the variables for your self

Should you "absolutely" need a custom table model based on AbstractTableModel , then you will need to provide the storage mechanisms which are used to store data within a given row/data yourself.

Typically, I define a POJO which represents the row and then add these to some kind of List , as it provides a simple mechanism for growing and shrinking the model

In your class you haven't declared the type of rowData . Presumably it's an 2 x 2 int array, but you haven't declared it, so the compiler cannot find the identifier. What you want to do is first declare rowData like

int[][] rowData = new int[r][v];

Then you can assign v to rowData as normal.

Example use of AbstractTableModel::setValueAt() .

    class MyTableModel extends AbstractTableModel {

        private final String[] columnNames = new String[]{"Col One", "Col Two"};
        private final Object[][] data = new String[][]{new String[]{"R1C1", "R1C2"}, new String[]{"R2C1", "R2C2"}};

        @Override
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }
......
rest of the code

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