Java 在JTree中的行之间添加垂直填充/空格?
是否可以在JTree中的节点行之间添加一些空格?我正在为节点图标使用自定义图像,我猜图像比标准节点图标大,因此节点图标非常靠近。如果有一点分隔,看起来会更好。要在树节点之间添加实际的间距,您必须修改UI并返回正确的AbstractLayoutCache后继者(默认情况下,JTree使用两个类,具体取决于行高值:FixedHeightLayoutCache或VariableHeightLayoutCache) 在节点之间添加一些间距的最简单方法是修改渲染器,使其具有一些附加边框,例如:Java 在JTree中的行之间添加垂直填充/空格?,java,swing,padding,nodes,jtree,Java,Swing,Padding,Nodes,Jtree,是否可以在JTree中的节点行之间添加一些空格?我正在为节点图标使用自定义图像,我猜图像比标准节点图标大,因此节点图标非常靠近。如果有一点分隔,看起来会更好。要在树节点之间添加实际的间距,您必须修改UI并返回正确的AbstractLayoutCache后继者(默认情况下,JTree使用两个类,具体取决于行高值:FixedHeightLayoutCache或VariableHeightLayoutCache) 在节点之间添加一些间距的最简单方法是修改渲染器,使其具有一些附加边框,例如: publi
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 );
}
这仍然比仅仅设置静态行高(如注释中提供给您的sub)要困难一些,但由于不同操作系统上可能存在不同的字体大小和样式,因此更好。这样你就不会在任何地方出现尺寸问题
顺便说一句,您还可以按自己喜欢的方式更改节点选择表示,这样您甚至可以在视觉上伪造间距。您使用过JTree的setRowHeight()方法吗?您可以将其设置为0,使每一行分别计算其高度。是的,这就是我最后所做的(同时将JTree的行高度设置为0,以便将高度计算延迟到单元渲染器)。效果很好。