java-防止在JTree中的节点扩展上选择节点
作者:互联网
我已经创建了一个JTree,其中的某些节点是自定义的,以显示它们可扩展,尽管它们还没有任何子节点.我遵循this thread来实现.
为什么?我想动态地加载树,因此当树扩展时,我将从服务器检索更多信息并将其显示在树上.
我遇到的问题是,当我展开这些节点之一时,它被选中,这不是默认节点的默认行为(您可以在不更改树选择的情况下展开它们).
如何解决这个问题以防止该节点在扩展时被选中?
解决方法:
我没有下面的代码的问题.您必须做其他事情,否则我们将无法看到您的代码.尝试采用以下代码并对其进行修改,以重现您遇到的问题.这样,您很有可能会发现自己在做不同的事情以及为什么会得到这种行为(另请参见SSCCE).
代码取自here
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class DynamicTree extends JFrame {
public class OutlineNode extends DefaultMutableTreeNode {
private boolean areChildrenDefined = false;
private int outlineNum;
private int numChildren;
public OutlineNode(int outlineNum, int numChildren) {
this.outlineNum = outlineNum;
this.numChildren = numChildren;
}
@Override
public boolean isLeaf() {
return false;
}
@Override
public int getChildCount() {
if (!areChildrenDefined) {
defineChildNodes();
}
return super.getChildCount();
}
private void defineChildNodes() {
// You must set the flag before defining children if you
// use "add" for the new children. Otherwise you get an infinite
// recursive loop, since add results in a call to getChildCount.
// However, you could use "insert" in such a case.
areChildrenDefined = true;
for (int i = 0; i < numChildren; i++) {
add(new OutlineNode(i + 1, numChildren));
}
}
@Override
public String toString() {
TreeNode parent = getParent();
if (parent == null) {
return String.valueOf(outlineNum);
} else {
return parent.toString() + "." + outlineNum;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new DynamicTree(5);
}
});
}
public DynamicTree(int n) {
super("Creating a Dynamic JTree");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Container content = getContentPane();
JTree tree = new JTree(new OutlineNode(1, n));
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(300, 475);
setVisible(true);
}
}
标签:jtree,swing,java 来源: https://codeday.me/bug/20191101/1982958.html