【发布时间】:2018-02-04 00:12:07
【问题描述】:
我在一帧中有 2 个 JTree,例如,如果我选择蓝色(从左侧树),它将填充右侧的树,之后,如果我现在选择红色,蓝色显示右侧不会消失以显示红色。
我尝试了三种不同的方法,例如 reloading()、repainting()、设置为 null,都没有。
DefaultTreeModel defMod1 = (DefaultTreeModel)jTree1.getModel();
defMod1.reload();
jTree1.repaint();
defMod1.setRoot(null);
我想要的是右侧的树显示左侧树上当前选择的内容。即如何重新加载或重绘右侧树以在左侧树上显示当前选择的内容?
我使用下面的方法来获取我实现的TreeSelectionListener接口的valueChange()中的当前选择。
DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
我需要帮助。 谢谢
PS:我已经尝试过DevilsHnd的解决方案,但仍然无法正常工作。部分代码如下。是的,我想要一种 clearTree() 函数。
@Override
public void valueChanged(TreeSelectionEvent e){
JTree treeSource = (JTree) e.getSource();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();//gets the selection
if(treeSource == jTree1 ){//if it is the tree on the left
if(node == null)//if a node is selected
return;
Object nodeInfo = node.getUserObject();
if(node.isLeaf()){
try {
String ipp = (String)nodeInfo;
root2 = new DefaultMutableTreeNode(InetAddress.getByName((String)nodeInfo)+ " | " + "Local Disk (C:)");//root node for the tree on the right
selectedPcIP = InetAddress.getByName(ipp).getHostAddress();
selectedIP = "\\\\" + selectedPcIP +"\\c$";
ArrayList creds = new BackItDb().getCreds();//gets user name and password from the database
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",creds.get(0).toString(),creds.get(1).toString());
try {
SmbFile file = new SmbFile("smb://"+selectedPcIP + "/" + System.getProperty("user.home").replace('C', 'c').replace(":", "$").replaceAll("[\\\\]","/")+"/",auth);//gets the folders from the selected PC
jTree1.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
createSecondTree(file,root2,selectedPcIP);//This is a function that creates the tree on the right(jtree2).
jTree1.setCursor(Cursor.getDefaultCursor());
treeModel2 = new DefaultTreeModel(root2);// treemodel for the tree on the right
jTree2.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
jTree2.setModel(treeModel2);// the tree on the right
}catch (UnknownHostException ex) {
Logger.getLogger(BackIt_Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
【问题讨论】:
-
最好能提供一个像样的minimal reproducible example 来回答您的问题
-
............ 还是不