javaswingmultiple-columnsjtreejtreetable

How can I add checkbox in tree table


I want to created a Tree with multi-columns. I found this tutorial here (German) and this answer (English). I want to add checkboxes in one column, but I have no idea how to do it. When I return a checkbox to JTreeTable, something show in execute is checkbox detail not checkbox object. How can I get something like this, pictured below?

like that


Solution

  • As shown in Taking the New Swing Tree Table for a Spin, cited here, your implementation of RowModel must return the correct type from getColumnClass() and the correct value from getValueFor(). Values of type Boolean.class will be rendered with a JCheckBox. The following implementations produce the image cited:

    image

    @Override
    public Class getColumnClass(int column) {
        switch (column) {
            case 0:
                return Date.class;
            case 1:
                return Long.class;
            case 2:
                return Boolean.class;
            case 3:
                return Boolean.class;
            case 4:
                return Boolean.class;
            default:
                assert false;
        }
        return null;
    }
    
    @Override
    public Object getValueFor(Object node, int column) {
        File f = (File) node;
        switch (column) {
            case 0:
                return new Date(f.lastModified());
            case 1:
                return f.length();
            case 2:
                return f.canRead();
            case 3:
                return f.canWrite();
            case 4:
                return f.canExecute();
            default:
                assert false;
        }
        return null;
    }
    

    I can't select checkbox.

    You need to return true in your implementation of isCellEditable() for the desired column(s) and update the node in your implementation of setValueFor() accordingly. When the cell editor concludes, your implementation of setValueFor() will be called, so verify that it updates the same value that will later be returned by getValueFor(). Optionally, you'll want to implement the TreeModel methods that manage the TreeModelListener list by using the scheme prescribed in an EventListenerList API; the DefaultTreeModel source code is a good example.