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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With