是否可以在 JTree 中的节点行之间添加一些空格?我为节点图标使用自定义图像,我猜这些图像比标准节点图标大,所以节点图标靠得很近。如果有一点分离会更好看。
最佳答案
要在树节点之间添加实际间距,您必须修改 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 );
}
这仍然比仅设置静态行高(如 Subs 在评论中提供给您的那样)要难一些,但由于各种操作系统上可能的字体大小和样式不同,因此更好。所以您不会在任何地方遇到尺寸问题。
顺便说一下,您还可以按照自己喜欢的方式更改节点选择表示,这样您甚至可以在视觉上伪造间距。
关于java - 在 JTree 中的行之间添加垂直填充/空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10645774/