在JTree中的行之间添加垂直填充/空格?

Xåp*_* - 5 java swing padding jtree nodes

是否可以在JTree中的节点行之间添加一些空格?我使用自定义图像作为节点图标,我猜图像比标准节点图标大,所以节点图标非常靠近.如果有一点分离,它看起来会更好.

Mik*_*rin 4

要在树节点之间添加实际间距,您必须修改 UI 并返回适当的 AbstractLayoutCache 后继(默认情况下,JTree 使用两个类,具体取决于行高值:FixedHeightLayoutCache 或 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 );
}
Run Code Online (Sandbox Code Playgroud)

这仍然比仅仅设置静态行高(正如 Subs 在评论中向您提供的那样)要困难一些,但由于各种操作系统上可能存在不同的字体大小和样式,所以它更好。所以你在任何地方都不会有尺寸问题。

顺便说一句,您还可以按照您喜欢的方式更改节点选择表示,这样您甚至可以在视觉上伪造间距。