1
我有一棵樹顯示網絡設備。樹被過濾,以便設備按位置和設備類型顯示。例如,節點「辦公室」將具有子節點「計算機」和「打印機」,每個節點都帶有設備。將子節點添加到選擇路徑[]
當我選擇位置節點時,我想選擇它下面的所有節點,並將其添加到我的樹的選擇路徑[]中,以使它們都高亮顯示。下面是我的代碼,但我無法弄清楚如何讓這個工作。
private class DefaultDeviceTreeCellRenderer extends DefaultTreeCellRenderer {
private JLabel label;
DefaultDeviceTreeCellRenderer() {
super();
label = new JLabel();
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object o = node.getUserObject();
if (o instanceof DefaultDevice) {
DefaultDevice defaultDevice = (DefaultDevice) o;
label.setIcon(defaultDevice.getIcon());
label.setText(defaultDevice.toString());
} else {
System.out.println("Cell Class= " + o.getClass());
//Set all children of this Component as selected.
label.setIcon(null);
label.setText("" + value);
TreePath[] selectionPaths = tree.getSelectionPaths();
if (selectionPaths == null) {
System.out.println("Nothing Selected. ");
} else {
//keep current selection path
//if there are leaf nodes, add their selection paths.
int i = 0;
while (i < node.getChildCount()) {
//add node.getNextLeaf().getPath() to selection Paths
ArrayList<TreePath> arrayList = new ArrayList<>(Arrays.asList(selectionPaths));
arrayList.add(new TreePath(((DefaultMutableTreeNode)node.getChildAt(i)).getPath()));
TreePath[] toArray = arrayList.toArray(new TreePath[arrayList.size()]);
this.printSelectionPath(selectionPaths);
this.printSelectionPath(toArray);
// tree.setSelectionPaths(toArray);
i++;
}
}
// System.out.println("Selection Paths.size="+selectionPaths.length);
// ArrayList arrayList = new ArrayList(Arrays.asList(selectionPaths));
// System.out.println("ChildNode Path=" + node.getPath()[a]);
}
label.setOpaque(true);
if (selected) {
label.setBackground(this.backgroundSelectionColor);
label.setForeground(this.textSelectionColor);
} else {
label.setBackground(this.backgroundNonSelectionColor);
label.setForeground(this.textNonSelectionColor);
}
return label;
}
private void printSelectionPath(TreePath[] selectionPaths) {
System.out.println("\nTreePath:");
for (int i = 0; i < selectionPaths.length; i++) {
System.out.println("Selection Path= " + selectionPaths[i]);
//TreePath treePath = new TreePath(node.getPath());
// System.out.println("TreePath= " + treePath);
}
}
你真的應該創建一個自定義的TreeSelectionModel:http://docs.oracle.com/javase/7/docs/api/javax/swing/tree/TreeSelectionModel.html – ControlAltDel
你能提供一個例子來完成這個? –
'我想選擇它下面的所有節點,並將其添加到我的樹的選擇路徑[]中,以便它們都被突出顯示出來嗎?您確定要更改SelectionModel來更改視圖嗎?基於是否存在父節點「位置」節點並且被選中,可以更容易地改變視圖。 – copeg