Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JTable non-editable

Tags:

java

swing

jtable

How to make a JTable non-editable? I don't want my users to be able to edit the values in cells by double-clicking them.

like image 793
Siddharth Raina Avatar asked Jan 02 '10 06:01

Siddharth Raina


People also ask

How do you make a JTable cell editable?

jTableAssignments = new javax. swing. JTable() { public boolean isCellEditable(int rowIndex, int colIndex) { return editable; }};

How do you clear a JTable row?

If using the DefaultTableModel , just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI. JTable table; … DefaultTableModel model = (DefaultTableModel) table.


1 Answers

You can override the method isCellEditable and implement as you want for example:

//instance table model DefaultTableModel tableModel = new DefaultTableModel() {      @Override     public boolean isCellEditable(int row, int column) {        //all cells false        return false;     } };  table.setModel(tableModel); 

or

//instance table model DefaultTableModel tableModel = new DefaultTableModel() {     @Override    public boolean isCellEditable(int row, int column) {        //Only the third column        return column == 3;    } };  table.setModel(tableModel); 

Note for if your JTable disappears

If your JTable is disappearing when you use this it is most likely because you need to use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor instead.

//instance table model DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {      @Override     public boolean isCellEditable(int row, int column) {        //all cells false        return false;     } };  table.setModel(tableModel); 
like image 152
nelson eldoro Avatar answered Oct 05 '22 01:10

nelson eldoro