How to adjust the vertical line & child node position according to the icon size in JTree?

StackOverflow https://stackoverflow.com/questions/20090419

  •  02-08-2022
  •  | 
  •  

문제

I made a custom styled JTree by implementing a TreeCellRenderer, which is like this:

              JPanel with BoxLayout X-Axis
-------------------------------------------------------------
|        |                                                  |
| JLabel |                    Text Area                     |
|  ICON  |     (JPanel with BoxLayout Y-Axis, 2 JLabels)    |
|        |                                                  |
-------------------------------------------------------------

But now I have a problem:

Screenshot

I am using a larger icon here, and the position of the vertical line which leads to children nodes is still the old one. I want the position vertical line and the child nodes to be adjusted -- moving the vertical line to the align with the center of the icon.

For now, the icon is 32x32px; in the future I'd like to introduce auto-resizing according to the total height of test area of the cell. So it's better to adjust the line position dynamically accroding to the actual size of the icon.

How should I do that?

도움이 되었습니까?

해결책

The horizontal position of the vertical lines is controlled by two properties of BasicTreeUI, left/rightChildIndent. So you can play with setting them based on the actual icon width, f.i. like:

// your standard icon
Icon icon = ...
BasicTreeUI ui = (BasicTreeUI) tree.getUI();
int iconWidth = icon.getIconWidth() / 2;
ui.setLeftChildIndent(iconWidth); 
ui.setRightChildIndent(iconWidth + 10); 

Note that you'll have to set those again whenever the LAF is changed at runtime.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top