如何使整个JTable无法编辑

时间:2014-11-09 18:20:26

标签: java swing jtable

我想为完整的JTable设置setEditable(false),但我不知道如何做到这一点。我经历了很多网站,但到处都找到了这段代码

DefaultTableModel model = new DefaultTableModel(6,7){
 public boolean isCellEditable(int row, int column)
 {
     return false;
 }
};

以上代码似乎特定的行和列不可编辑,但如何才能使整个表格无法编辑。

这是我的代码表,数据来自MySQL数据库 -

GridBagConstraints gbc = new GridBagConstraints();
jbutton1=new JButton("Close");
setTitle("Customer List");

JPanel panel = new JPanel(new GridBagLayout());
this.getContentPane().add(panel);

String[] columnNames = {"Account No", "Customer Name", "Account Type", "Credit Limit"};

DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);

table = new JTable();
table.setModel(model); 
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

table.setFillsViewportHeight(true);

JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 

String accno= "";
String name= "";
String type = "";
String limit = "";
try
{
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/banking_prj","root","");
    String sql = "select * from customer ORDER BY account_no";
    PreparedStatement ps = con.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while(rs.next())
    {
        accno = rs.getString(1);
        name = rs.getString(2);
        type = rs.getString(3);
        limit = Double.toString(rs.getDouble(4));
        model.addRow(new Object[]{accno, name, type, limit});
    }
}
catch(Exception ex)
{
    JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
    JOptionPane.ERROR_MESSAGE);
}

谢谢

1 个答案:

答案 0 :(得分:3)

public boolean isCellEditable(int row, int column) {
    return false;
}
  

以上代码似乎特定的行和列不可编辑,但如何才能使整个表格无法编辑。

无论行和列的值是什么,该方法都返回false。因此,对于所有行和所有列,相应的单元格是不可编辑的,这正是您想要的。