Put JTable in the JTree

前端 未结 2 630
无人共我
无人共我 2020-11-27 21:59

in connection with thread Jtable as a Jtree Node I put JTable to JTree, but JTree View isn\'t rendered correctly on start_up, how can I setPreferredSize

2条回答
  •  青春惊慌失措
    2020-11-27 22:29

    You might just get rid of the ScrollPane and lay out the header and table in the panel directly (with a null LayoutManager so you can control everything yourself):

    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;
        }
    }
    

提交回复
热议问题