简体   繁体   中英

JTable set specific cells not editable?

I would like to set some cells not editable in my JTable. I also searched for some solutions like this one , but I don't get it working...

This is my code so far:

public void cellEditableForum(JTable tempTable){
        DefaultTableModel tempTableModel = (DefaultTableModel) tempTable.getModel();
        int rows = tempTableModel.getRowCount();
        int columns = tempTableModel.getColumnCount();

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (j == 0 || j == 5) {
                    //TODO: Make cell not editable!
                    tempTableModel.fireTableCellUpdated(i, j);
                    System.out.println("Row: " + i + " Cell: " + j + tempTableModel.isCellEditable(i, j));
                }
            }
        }
    }

And no, I CANNOT override the isCellEditable() function because I want to set only a few and selected cells not editable for different tables. Thats the reason, why I have created a function and the if check!

Can somebody help me please?

Here is special table model which supports uneditable cells

import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

public class EditableTableModel extends DefaultTableModel {

    private Map<String, Boolean> editableMap = new HashMap<>();

    public void setCellEditable(int row, int column, boolean editable) {
        editableMap.put(row + ":" + column, editable);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return Boolean.FALSE != editableMap.get(row + ":" + column);
    }

    public static void main(String[] args) {
        JFrame frm = new JFrame("Test frame");
        EditableTableModel model = new EditableTableModel();
        model.setRowCount(10);
        model.setColumnCount(5);
        model.setCellEditable(0, 0, false);
        frm.add(new JScrollPane(new JTable(model)));
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }
}

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