A
A
Alecxandrys2016-11-07 22:28:18
Java
Alecxandrys, 2016-11-07 22:28:18

How to edit a cell in TabelModel?

Good afternoon!
There is a specified TableModel, but it is impossible to change the values ​​in the table created by it

import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.util.HashSet;
import java.util.Set;


class ConjunctionTableModel implements TableModel {
    private Set<TableModelListener> listeners = new HashSet<>();
    private int G1[][];

    ConjunctionTableModel(int G1[][])
    {
     this.G1=G1;
    }
    @Override
    public int getRowCount() {
        return G1.length;
    }

    @Override
    public int getColumnCount() {
        return G1.length + 1;
    }

    @Override
    public String getColumnName(int columnIndex) {
        if (columnIndex == 0) return "";
        return "x" + columnIndex;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        if (columnIndex == 0) return String.class;
        return int.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return columnIndex != 0;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            return "x" + (rowIndex + 1);
        }

        return G1[rowIndex][columnIndex - 1];
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (!(aValue instanceof String)) {
            if ((int) aValue == 0 || (int) aValue == 1) {
                G1[rowIndex][columnIndex - 1] = (int) aValue;
            }
        }

    }

    @Override
    public void addTableModelListener(TableModelListener l) {
        listeners.add(l);
    }

    @Override
    public void removeTableModelListener(TableModelListener l) {
        listeners.remove(l);
    }
}


The table is created through the following
JTable table = new JTable(new ConjunctionTableModel(G1)); 
JScrollPane scrollPane = new JScrollPane(table);

where G1 is a matrix of int values, only 0 and 1 are allowed.

How can I fix the code so that I can edit the values ​​in the table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alecxandrys, 2016-11-10
@Alecxandrys

And everything elementary is simple

@Override
    public Class<?> getColumnClass(int columnIndex) {
        if (columnIndex == 0) return String.class;
        return Integer.class;
    }

Using the place of the primitive int wrapping Integer turned out to be enough and everything worked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question