我渲染了一个复选框节点树。 渲染器使用(复选框+文件夹,如图标)和叶节点(仅复选框)呈现父节点。
我已渲染它,现在我想让它可编辑。 (即)当我点击它时,必须选中并取消选中复选框。
我尝试写一个编辑器。但我不清楚如何写它。请指导我如何实现这一目标。
非常感谢提前。
我用Vector构建了树。该向量称为NamedVector,它包含父节点对象。父节点对象保存叶节点。叶节点的类型为CheckBoxNode。
public class CheckBoxNodeRenderer implements TreeCellRenderer{
NonLeafRenderer nonLeafRenderer = new NonLeafRenderer();
protected JCheckBox check;
protected JLabel label;
public JPanel panel;
CheckBoxNode checkNode;
public JCheckBox getLeafRenderer()
{
return leafRenderer;
}
public CheckBoxNodeRenderer()
{
panel = new JPanel();
panel.setLayout(new BorderLayout());
check = new JCheckBox();
label = new JLabel();
Font fontValue;
fontValue = UIManager.getFont("Tree.font");
if (fontValue != null) {
leafRenderer.setFont(fontValue);
}
Boolean booleanValue = (Boolean) UIManager
.get("Tree.drawsFocusBorderAroundIcon");
leafRenderer.setFocusPainted((booleanValue != null)
&& (booleanValue.booleanValue()));
selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
selectionForeground = UIManager.getColor("Tree.selectionForeground");
selectionBackground = UIManager.getColor("Tree.selectionBackground");
textForeground = UIManager.getColor("Tree.textForeground");
textBackground = UIManager.getColor("Tree.textBackground");
}
///////////////////
/**
* Approach by returning a panel .
*/
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean isSelected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
String stringValue = tree.convertValueToText(value, isSelected,
expanded, leaf, row, hasFocus);
panel.setEnabled(true);
if(leaf){
if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
checkNode = (CheckBoxNode)node.getUserObject();
check.setSelected(checkNode.isSelected());
label.setFont(tree.getFont());
label.setText(value.toString());
label.setIcon(null);
panel.removeAll();
panel.add(check,BorderLayout.WEST);
panel.add(label);
panel.setVisible(true);
}
}
else if(!leaf){
if ((value != null) && (value instanceof DefaultMutableTreeNode) ) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
Object parent = (Object)node.getUserObject();
System.err.println(parent.toString());
NamedVector parentNode = (NamedVector) parent;
check.setSelected(parentNode.isSelected());
label.setFont(tree.getFont());
label.setText(parentNode.toString());
label.setIcon(UIManager.getIcon("Tree.openIcon"));
panel.removeAll();
panel.add(check,BorderLayout.WEST);
panel.add(label);
panel.setVisible(true);
}
}
return panel;
}
答案 0 :(得分:0)
问题在于你不是在听事件。在getTreeCellRendererComponent方法中,创建一个侦听器,然后确保通过nodeChanged方法告诉树模型您已更改节点。以下应该可行(您可能必须使一些变量最终在内部类中使用它们):
check.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
checkNode.setSelected(check.isSelected());
DefaultTreeModel dtm = (DefaultTreeModel)tree.getModel();
dtm.nodeChanged(node);
}
});