Adding vertical indentation / spaces between lines in JTree?

Is it possible to add space between node strings in JTree? I use custom images for node icons, and I think the images are larger than standard node icons, so the node icons are very close to each other. It would be better if there was a bit of separation.

+5
source share
1 answer

To add the actual spacing between the tree nodes, you will have to change the user interface and return a suitable AbstractLayoutCache successor (by default, JTree uses two classes depending on the line height value: FixedHeightLayoutCache or VariableHeightLayoutCache).

- , , :

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

, ( Subs), - . , .

, node , , .

+3

All Articles