java - JTable 删除或隐藏或禁用特定单元格?

标签 java swing jtable tablecellrenderer tablecelleditor

我想知道以下是否可行以及如何做到这一点。我想删除或隐藏或禁用选择 我的表格中的“空”单元格:

enter image description here

以下是设置表模型的代码,在此代码之后我只是用数据填充表:

myTable.setModel(new javax.swing.table.DefaultTableModel(
        new Object[][]{
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null}
        },
        new String[]{
            null, null, null
        }) {
    Class[] types = new Class[]{
        java.lang.String.class, java.lang.String.class, java.lang.String.class
    };
    boolean[] canEdit = new boolean[]{
        false, false, false
    };

    @Override
    public Class getColumnClass(int columnIndex) {
        return types[columnIndex];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit[columnIndex];
    }
}); 

最佳答案

好吧,经过一番黑客攻击后,我想我有一个可能的解决方案给你。

table.setCellSelectionEnabled(true);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setDefaultRenderer(Object.class, new Renderer());
<小时/>
public class Renderer extends DefaultTableCellRenderer {

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {

    if (table.getValueAt(row, column) == null && isSelected) {
        table.clearSelection();

        return super.getTableCellRendererComponent(table, value, false, false,
                row, column);
    } else {
        return  super.getTableCellRendererComponent(table, value, isSelected,
                hasFocus, row, column);
    }
}

}

这只有在你有的情况下才有效

table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

已启用。并且空单元格仍然具有焦点。但它可能足以满足您的要求

关于java - JTable 删除或隐藏或禁用特定单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13630572/

相关文章:

java - java中通过mac终端操作文件

java - 如何更改 JTextArea 的默认光标位置?

java - 键绑定(bind)不适用于某些键,例如插入、删除

java - JTable中的数据没有改变

java - 如何在 JInternalFrame 的 ScrollPane 中动态设置 JTable 的宽度

java - JTable 中的搜索结果

java - 数据库-JTable交互

java - 如何从map/reduce函数输出不同类型的键,值对?

java - 如何使用 JPA 获取动态Where子句数据

java - 如何使用 spring java 配置在单例 bean 中生成原型(prototype)对象