把JTable放在JTree中

时间:2012-01-12 23:03:30

标签: java swing jtable jtree renderer

与线程Jtable as a Jtree Node有关我把JTable放到了JTree上,但JTree View在start_up上没有正确呈现,我怎样setPreferredSizeJTable,因为{ {1}}缩放PreferredScrollableViewportSize,渲染JTable +一个TableHeader,其中一个Row仍处于隐藏状态,但在展开Node后,TreeRenderer会更改并重新绘制{{1}到预期的Row

enter image description here enter image description here

setPreferredSize

2 个答案:

答案 0 :(得分:4)

摆脱scrollPane,无论如何都是功能失调(到目前为止我同意Russell :-)并使用适当的LayoutManager将表及其标题添加到面板中:

public MyTableInTreeCellRenderer() {
    super();
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    table = new JTable();
    add(table.getTableHeader());
    add(table);
}

你可能需要稍微调整视觉效果,左边和上边框线丢失 - 不完全确定哪个组件正常绘制它们,可能是scrollPane

修改

忘记:在计算渲染组件所需的大小(在ui委托中完成,即VariableHeightLayoutCache)时查询scrollPane的prefSize的原因是还没有配置标题的scrollPane。在将面板添加到rendererPane之前进行查询,完成配置在表的addNotify中完成,只有在将面板添加到层次结构后才会发生

答案 1 :(得分:3)

您可能只是摆脱ScrollPane并直接在面板中布置标题和表格(使用null LayoutManager,以便您可以自己控制所有内容):

static class TableTreeCellRenderer extends JPanel implements TreeCellRenderer {
    private final JTable table;

    TableTreeCellRenderer() {
        table = new JTable();
        setLayout(null);
        add(table.getTableHeader());
        add(table);
    }

    public Dimension getPreferredSize() {
        Dimension headerSize = table.getTableHeader().getPreferredSize();
        Dimension tableSize = table.getPreferredSize();

        return new Dimension(Math.max(headerSize.width, tableSize.width),
                headerSize.height + tableSize.height);
    }

    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        int headerHeight = table.getTableHeader().getPreferredSize().height;
        table.getTableHeader().setBounds(0, 0, width, headerHeight);
        table.setBounds(0, headerHeight, width, height - headerHeight);
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        final String v = (String) ((DefaultMutableTreeNode) value).getUserObject();
        table.setModel(new DefaultTableModel(new Object[][] { 
                { v + "0", "1" },
                { v + "2", "3" }
        }, new Object[] { "id", "value" } ));
        invalidate();
        return this;
    }
}