Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding vertical padding/space between rows in a JTree?

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.

like image 531
XåpplI'-I0llwlg'I - Avatar asked May 18 '12 01:05

XåpplI'-I0llwlg'I -


1 Answers

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.

like image 179
Mikle Garin Avatar answered Sep 27 '22 01:09

Mikle Garin