我们能否使用 Java 来防止 JTree 中的节点和子节点折叠?\n
是的,我们可以使用 setExpandedState() 方法来防止 JTree 中的节点和子节点折叠。此方法设置此 JTree 的展开状态。如果 state 为 true,则所有路径和路径的父节点都被标记为展开。
以下是一个使用 Java 来防止 JTree 中的节点和子节点折叠的示例 -
示例
package my; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Demo"); DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project"); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App"); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website"); DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp"); node.add(node1); node.add(node2); node.add(node3); DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website"); DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website"); DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website"); DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app"); DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app"); DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp"); node1.add(one); node1.add(two); node1.add(three); node2.add(four); node2.add(five); node3.add(six); JTree tree = new JTree(node) { protected void setExpandedState(TreePath path, boolean state) { if (state) { super.setExpandedState(path, state); } } }; for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } tree.putClientProperty("JTree.lineStyle", "Angled"); int begnRow = 0; String prefix = "A"; TreePath treePath = tree.getNextMatch(prefix, begnRow, Position.Bias.Forward); System.out.println("Node = "+treePath); tree.setRowHeight(25); frame.add(tree); frame.setSize(550,400); frame.setVisible(true); } }
输出
广告