我正在使用包含4列的JTable
,如何设置JTable
,以选择一行,但用户不应更改该行的值?
Jtable.setEnabled(false);
这句话对我不起作用,因为用户无法选择该行。
如何用你的答案替换这段代码?
public void setModel()
{
String[] colNames = {"Name","Email","Department","Status"};
TableModel model = new DefaultTableModel(colNames,500);
table.setModel(model);
String insert = "select * from " + deptName;
try
{
conn = ac.getConnection();
stmt = conn.prepareStatement(insert);
rs = stmt.executeQuery();
int row = 0;
while(rs.next())
{
String[] rowData = new String[5];
for(int i=1;i<=4;i++)
{
rowData[i-1] = rs.getString(i);
}
model.setValueAt(rowData[0], row, 0);
model.setValueAt(rowData[1], row, 1);
model.setValueAt(rowData[2], row, 2);
model.setValueAt(rowData[3], row, 3);
row++;
}
}catch(SQLException s){}
catch(ClassNotFoundException e)
{e.printStackTrace();}
finally
{
try
{
if(rs != null){rs.close();}
if(stmt != null){stmt.close();}
if(conn != null) {conn.close();}
}
catch(SQLException e){}
}
}
答案 0 :(得分:1)
根据您创建表格模型的方式,您需要覆盖TableModel#isCellEditable
,并为您想要不可编辑的所有单元格返回false
查看How to use tables了解详情
答案 1 :(得分:1)
像这样扩展DefaultTableModel
private class NoCellEditTableModel extends DefaultTableModel{
@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
}
然后将其设置为JTable
答案 2 :(得分:1)
为表格设置模型并覆盖isCellEditable
方法
jtable.setModel(new TableModel() {
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
});
答案 3 :(得分:1)
偏见我无法抗拒建议使用JXTable(在SwingX project中:它支持配置视图的可编辑性,每列和每个表
// to disable editing for a particular column
table.getColumnExt(columnIndex).setEditable(false);
// to disable editing for the complete table
table.setEditable(false);