Search code examples
javaswingjpaneljtreetreecellrenderer

How do I make my TreeCellRenderer fill my JTree?


How do I make my tree cells fill the width of my JTree:

JTree tree = new JTree();
tree.setCellRenderer(new TreeCellRenderer() { 
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value,
        boolean selected, boolean expanded, boolean leaf, int row, 
        boolean hasFocus) {
            // TODO: How do I make this panel fill the width 
            // of the JTree?
            JPanel panel = new JPanel();
            panel.add(new JLabel("ITEM");
            return panel;
        }
});
add(tree);

Solution

    • JPanel panel = new JPanel();, JPanel is container,

    • empty JPanel by default returns zero Dimension,

    • only empty JPanel (AFAIK only) returns 10px in BorderLayotu, in the case that JPanels are placed to the NORTH, SOUTH, WEST, SOUTH areas, then created very nice 10pxs EmptyBorders

    • have to override getPreferredSize for JPanel, the same ways as is required for Painting in Swing

    • no idea for why reason you put JPanel as Renderers JComponent into JTree, maybe there is/are another way(s), sure for better help sooner post an SSCCE