【问题标题】:Java Tables - Set editable columns and not editableJava Tables - 设置可编辑的列而不是可编辑的
【发布时间】:2018-04-26 17:12:07
【问题描述】:

我有一个有 2 列的 JTable。 第一列存储ImageIcons,第二列存储String。

我想将第二列设置为可编辑,但第一列不可编辑。

完整代码:https://pastebin.com/7qge1PVc

这是我的代码示例:

File[] files = chooser.getSelectedFiles(); //Image files array
String[] columnNames = {"Image", "Description"};
Object[][] data = new Object[files.length][2]; //To fill with images and descriptions
int count = 0;

for(File imatge: files){
    if(accept(imatge)){
        imgBanknote = new ImageIcon( new ImageIcon(imatge.getAbsolutePath()).getImage().getScaledInstance(150, 120, Image.SCALE_SMOOTH));
        data[count][0] = imgBanknote;
        data[count][1] = imatge;
        count++;
    }
}

DefaultTableModel model = new DefaultTableModel(data, columnNames){
    //  Returning the Class of each column will allow different
    //  renderers to be used based on Class
    @Override
    public Class getColumnClass(int column) {
        return getValueAt(0, column).getClass();
    }
    @Override
    public boolean isCellEditable(int row, int column){
        return column != 0;
    }

};

taula.setModel(model); //Set model to JTable
taula.setPreferredScrollableViewportSize(taula.getPreferredSize());

问题是我用来渲染图像的getColumnClass 方法,这使得第二列不可编辑。我不知道如何解决。

【问题讨论】:

  • 代码看起来很合理。发布一个正确的minimal reproducible example 来说明问题。这就是您所需要的一个包含 2 列的表,并将硬编码数据添加到表中。
  • 这里是完整的 JDialog 代码pastebin.com/7qge1PVc
  • 没有要求您提供完整代码。您被要求提供minimal reproducible example。 MCVE 的重点是简化问题。正如我所说的数据来自哪里无关紧要,因此可以轻松地对数据进行硬编码以进行简单测试。

标签: swing jtable imageicon defaulttablemodel


【解决方案1】:

解决了!

问题是data[count][1] = imatge;。 我在表格中添加了一个文件,而 JTable 中的文件不可编辑。

为了解决问题,我已将data[count][1] = imatge; 替换为data[count][1] = imatge.getName();,现在它是一个字符串并且可以编辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2015-11-14
    相关资源
    最近更新 更多