java DefaultTableModel 使单元格不可编辑 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12840153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:25:44  来源:igfitidea点击:

DefaultTableModel make cell not editable JTable

javaswingjtableoverridingdefaulttablemodel

提问by Dave

I have an JAVA project and want to make my JTable with a DefaultTableModel non-editable. I know a work-around to do this, called:

我有一个 JAVA 项目,想让我的 JTable 带有一个不可编辑的 DefaultTableModel。我知道一种解决方法,称为:

JTable table = new JTable(...){  
  public boolean isCellEditable(int row, int column){  
    return false;  
  }  
};  

Like said: i dont like this. This is not according the rules of my school training.

就像说:我不喜欢这个。这不符合我学校的训练规则。

Is there any way to do this? Maybe is there a good way. I hope so!

有没有办法做到这一点?或许有什么好办法。但愿如此!

回答by JB Nizet

You should not subclass the JTable itself, but the table model:

您不应该对 JTable 本身进行子类化,而是对表模型进行子类化:

DefaultTableModel myModel = new DefaultTableModel(...) {
    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
}

Or even better, don't use a DefaultTableModel, and use an AbstractTableModel that directly gets the information in your business objects rather than copying all the information from the business objects to Vectors.

或者更好的是,不要使用 DefaultTableModel,而使用 AbstractTableModel 直接获取业务对象中的信息,而不是将业务对象中的所有信息复制到 Vectors。

回答by Adel

select Jtable , and don't forget to create table model (DefaultTableModel TableModel)

选择 Jtable ,不要忘记创建表模型(DefaultTableModel TableModel)

JTable table_1 = new JTable (TableModel){public boolean isCellEditable(int row,int column)  
        {switch(column){             
           case 4:  // select the cell you want make it not editable 
             return false;  
         default: return true;}  
        }};