How to make JTable inaccessible for editing

How to make JTable inaccessible for editing? I do not want my users to be able to edit values ​​in cells by double-clicking them.

+82
java swing jtable
Jan 02 '09 at 6:49
source share
7 answers

You can use TableModel .

Define the class as follows:

 public class MyModel extends AbstractTableModel{ //not necessary } 

In fact, isCellEditable() is false by default, so you can omit it. (see http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html )

Then use the setModel() method of your JTable .

 JTable myTable = new JTable(); myTable.setModel(new MyModel()); 
+17
Jan 02 '09 at 7:00
source share

You can override the isCellEditable method and implement it as you like, 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 if your JTable disappears

If your JTable disappears when you use it, it is most likely because you should use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor DefaultTableModel(Object[][] data, Object[] columnNames) 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); 
+130
Jun 28 '10 at 16:01
source share

just add

 table.setEnabled(false); 

It works great for me.

+35
Aug 16 2018-12-12T00:
source share
 table.setDefaultEditor(Object.class, null); 
+17
Apr 01 '16 at 12:28
source share

If you create a TableModel automatically from a set of values ​​(using the "new JTable (Vector, Vector)"), it may be easier to remove editors from columns:

 JTable table = new JTable(my_rows, my_header); for (int c = 0; c < table.getColumnCount(); c++) { Class<?> col_class = table.getColumnClass(c); table.setDefaultEditor(col_class, null); // remove editor } 

Without editors, the data will not be edited.

+7
Dec 13 '13 at 14:13
source share

create a new class DefaultCellEditor:

 public static class Editor_name extends DefaultCellEditor { public Editor_name(JCheckBox checkBox) { super(checkBox); } @Override public boolean isCellEditable(EventObject anEvent) { return false; } } 

and use setCellEditor:

 JTable table = new JTable(); table.getColumn("columnName").setCellEditor(new Editor_name(new JCheckBox())); 
+2
Jul 23 '14 at 8:50
source share

I used this and it worked: it is very simple and works great.

 JTable myTable = new JTable(); myTable.setEnabled(false); 
+2
Jan 27 '17 at 15:49
source share



All Articles