问题
This question already has an answer here:
- How to make a JTable non-editable 7 answers
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());
}
}
}
回答1:
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
回答2:
You are adding another JTable
in your code, you are confusing between the one extending and the other one added to the JFrame!
Add these invocations after fixing the above:
table.setFocusable(false);
table.setRowSelectionAllowed(true);
回答3:
Your class extends JTable and you override the isCellEditable(...)
method.
But then you create a new JTable that you add to the frame and you do NOT override the isCellEditable(..)
method of that JTable.
If you want to extend JTable, then don't create a new JTable inside that class.
来源:https://stackoverflow.com/questions/24726896/how-to-make-cells-of-jtable-non-editable-but-selectable