我正在使用下面的这段代码:
class CountryTreeCellRenderer implements TreeCellRenderer {
private JLabel label;
CountryTreeCellRenderer() {
label = new JLabel();
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof Country) {
Country country = (Country) o;
label.setIcon(new ImageIcon(country.getFlagIcon()));
label.setText(country.getName());
} else {
label.setIcon(null);
label.setText("" + value);
}
return label;
}
}
由于我正在传递/返回标签,因此在选择 中的任何组件时JTree
,不会出现选择颜色。我尝试使用:
JComponent comp = (JComponent) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
comp.setOpaque(true);
if(selected)
comp.setBackground(Color.RED);
但是如果我 return comp
,那么树的输出不会像预期的那样出现。
如何解决相同的问题?
我没有为此实现任何编辑器。