我正在使用下面的代码:
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);但是如果我返回comp,那么树的输出就不会像预期的那样出现。
如何解决同样的问题?
I没有为相同的.实现任何编辑器
发布于 2012-01-29 09:20:01
请看一下source code of the DefaultTreeCellRenderer,它扩展了JLabel,并且完全能够设置背景色。我复制粘贴了下面的相关行:
if (selected)
{
super.setBackground(getBackgroundSelectionColor());
setForeground(getTextSelectionColor());
if (hasFocus)
setBorderSelectionColor(UIManager.getLookAndFeelDefaults().
getColor("Tree.selectionBorderColor"));
else
setBorderSelectionColor(null);
}
else
{
super.setBackground(getBackgroundNonSelectionColor());
setForeground(getTextNonSelectionColor());
setBorderSelectionColor(null);
}发布于 2012-02-01 15:52:51
是的,正如罗宾所解释的那样,它基本上起了作用。
if(selected){
label.setBackground(Color.YELLOW);
label.setForeground(Color.GREEN);
}else
{
label.setBackground(Color.WHITE);
label.setForeground(Color.BLACK);
//setBorderSelectionColor(null);
}足够的
https://stackoverflow.com/questions/9051463
复制相似问题