我有一个JTree与几个节点,并且每个节点都有一个不同的关联JPanel我想要显示给用户。我已经使用了一个自定义的TreeCellRenderer,而且我的代码目前正常工作,但是(我认为)它有点过于笨拙,我对此有所担心如何根据JTree选择优化显示不同的JPanel
1)如果我只保留一个选定的树节点,将不断刷新JPanel。一旦选定的节点显示了JPanel一次,我不希望它再次被选中,除非另一个节点被选中。 2)如果用户在我的定时器运行node1时选择了不同的节点(我们说节点2),我不想打扰显示node1的JPanel,因为用户已经离开它。
这里是我的兴趣代码:
Component ret = super.getTreeCellRendererComponent(tree, value,
selected, expanded, leaf, row, hasFocus);
DefaultMutableTreeNode entry = (DefaultMutableTreeNode)value;
// if the node is selected
if(sel)
{
// set the background of the node
setBackgroundNonSelectionColor(new Color(0x91, 0xC5, 0xFF));
// display the JPanel for the node
displayPanel(entry);
}
else
{
// if the node isn't selected then no background selection color
setBackgroundNonSelectionColor(Color.WHITE);
}
return ret;
displayPanel功能:
// display the node's JPanel after sleeping for 1s
private void displayPanel(final DefaultMutableTreeNode entry)
{
Thread thr = new Thread(){
public void run(){
// sleep for 1000ms
CF.sleep("1000");
// display the panel for this node
CF.displayPanel(entry);
}
};
thr.start();
}
说实话,DefaultTreeCellRenderer还是有点混乱给我。我会很感激任何有关如何有效地运行的建议。
第一段代码的上下文不是很清楚,它包含在哪里?另外,为什么不仅仅使用树选择事件来选择'JPanel'来显示? – asermax 2013-03-01 18:53:44
对不起,代码位于扩展DefaultTreeCellRenderer的类中。如果您想要更多的上下文,我可以包含其余的代码。我没有考虑使用树选择事件,因为我目前没有在那里听一个动作,但这可能是一个更好的主意。 – Matt 2013-03-01 18:56:32