Adding vertical padding/space between rows in a JTree?
Asked Answered
S

1

7

Is it possible to add some blank space between node rows in a JTree? I am using custom images for the node icons and I guess the images are larger than the standard node icons, so the node icons sit very close together. It would look nicer if there was a bit of separation.

Santiago answered 18/5, 2012 at 1:53 Comment(1)
Have you used the JTree's setRowHeight() method? You can set it to 0 to make each row calculate its height individually.Lulualaba
A
4

To add an actual spacing between tree nodes you will have to modify the UI and return a proper AbstractLayoutCache successor (by default JTree uses two classes, depending on the row height value: FixedHeightLayoutCache or VariableHeightLayoutCache).

The easiest way to add some spacing between nodes is to modify renderer, so it will have some additional border, for example:

public static void main ( String[] args )
{
    JFrame frame = new JFrame ();

    JTree tree = new JTree ();
    tree.setCellRenderer ( new DefaultTreeCellRenderer ()
    {
        private Border border = BorderFactory.createEmptyBorder ( 4, 4, 4, 4 );

        public Component getTreeCellRendererComponent ( JTree tree, Object value, boolean sel,
                                                        boolean expanded, boolean leaf, int row,
                                                        boolean hasFocus )
        {
            JLabel label = ( JLabel ) super
                    .getTreeCellRendererComponent ( tree, value, sel, expanded, leaf, row,
                            hasFocus );
            label.setBorder ( border );
            return label;
        }
    } );
    frame.add ( tree );

    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    frame.setVisible ( true );
}

This is still a bit harder than just setting the static row height (as Subs offered to you in comment), BUT it is better due to different possible font sizes and styles on various OS. So you won't have size problems anywhere.

By the way, you can also change the node selection representation the way you like, that way you can even fake the spacing visually.

Anacoluthia answered 18/5, 2012 at 13:3 Comment(1)
Yep, this is what I ended up doing (along with setting the JTree's row height to 0 so that it defers height calculation to the cell renderer). Works quite well.Sardou

© 2022 - 2024 — McMap. All rights reserved.