I have overridden the isCellEditable() method of class JTable in my code to make the cells of my JTable non-editable but selectable, but the cells are still editable. How do I solve this problem?
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class A extends JTable{
JFrame frame = new JFrame();
Object data[][] = {{"1","Jahanzeb"},{"2","Ahmed"},{"3","Shaikh"}};
String col[] = {"#","Names"};
DefaultTableModel tableModel = new DefaultTableModel(data, col);
JTable table = new JTable(tableModel);
JScrollPane scroll = new JScrollPane(table);
public static void main(String arg[]){
new A();
}
public A() {
table.addMouseListener(new Click());
table.setModel(tableModel);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.add(table);
frame.setVisible(true);
}
@Override
public boolean isCellEditable(int row, int column){
return false;
}
class Click extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2)
System.out.println(table.getSelectedRow());
}
}
}
I believe you need to override the isCellEditable() method of the TableModel rather than the JTable, like so:
public class NonEditableModel extends DefaultTableModel {
NonEditableModel(Object[][] data, String[] columnNames) {
super(data, columnNames);
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
It is also possible to simply override the method using an anonymous class.
DefaultTableModel tableModel = new DefaultTableModel(data, col) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
This question demonstrates how to perform the override inline, which is handy if you only need to instantiate the TableModel once: How to make a JTable non-editable