所有
最近两天试图为JTree动态设置不同的行高,但是没有成功。下面是我想要实现的目标......以下是我的尝试:
(1)使用setRowHeight(0),以便节点查询它的当前单元格渲染器
(2)设置从jtree的单元格渲染器返回的组件的PreferredSize(Dimension d)。
(3)更改渲染器本身的rowheight,我现在理解不应该这样做。
我不知道如何在同一列上设置不同的单元格渲染器,例如下面的列A,也许我可以硬编码不同的行高。
任何人都有任何提示或技巧,或者更好的仍然是一个有效的例子,我的脑子被炸了,我似乎已经筋疲力尽了所有其他资源......这应该是可能的,对吗?
答案 0 :(得分:2)
(1)
和(2)
使用JDK1.8.0_51
上的Windows 10
可以正常使用我:
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class RowHeightsDynamicallyTest {
public JComponent makeUI() {
JTree tree = new JTree() {
@Override public void updateUI() {
setCellRenderer(null);
super.updateUI();
setCellRenderer(new RowHeightsDynamicallyRenderer());
setRowHeight(0);
setRootVisible(false);
setShowsRootHandles(false);
}
};
return new JScrollPane(tree);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
for (UIManager.LookAndFeelInfo laf: UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new RowHeightsDynamicallyTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class RowHeightsDynamicallyRenderer extends DefaultTreeCellRenderer {
private int height;
@Override public Component getTreeCellRendererComponent(
JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
JLabel l = (JLabel) super.getTreeCellRendererComponent(
tree, value, selected, expanded, leaf, row, hasFocus);
l.setFont(tree.getFont().deriveFont(leaf ? 16f : 48f));
height = leaf ? 20 : 60;
//use dummy height Icon: l.setIcon(new DummyHeightIcon(height));
//use <td> height: l.setText(String.format("<html><table><tr><td height='%d'>%s", height, value));
return l;
}
@Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.height = height;
return d;
}
}
// class DummyHeightIcon implements Icon {
// private final int height;
// public DummyHeightIcon(int height) {
// this.height = height;
// }
// @Override public void paintIcon(Component c, Graphics g, int x, int y) {}
// @Override public int getIconWidth() {
// return 0;
// }
// @Override public int getIconHeight() {
// return height;
// }
// }