如何允许在 JTree 中连续选择节点?
连续选择是指共享边框,例如在 JTree 中选择某个节点的兄弟节点。若要允许连续选择节点,请将选择模式设置为 CONTIGUOUS_TREE_SELECTION −
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
以下是一个在 JTree 中允许连续选择节点的示例 −
示例
package my; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Demo"); DefaultMutableTreeNode node = new DefaultMutableTreeNode("Products"); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Clothing"); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Electronics"); DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Home Decor"); DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Furniture"); node.add(node1); node.add(node2); node.add(node3); node.add(node4); DefaultMutableTreeNode one = new DefaultMutableTreeNode("Shirt"); DefaultMutableTreeNode two = new DefaultMutableTreeNode("Trousers"); DefaultMutableTreeNode three = new DefaultMutableTreeNode("Jeans"); DefaultMutableTreeNode four = new DefaultMutableTreeNode("Mobiles"); DefaultMutableTreeNode five = new DefaultMutableTreeNode("Camera"); DefaultMutableTreeNode six = new DefaultMutableTreeNode("Tablet"); DefaultMutableTreeNode seven = new DefaultMutableTreeNode("Paintings"); DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Showpieces"); DefaultMutableTreeNode nine = new DefaultMutableTreeNode("Wardrobes"); DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Bean Bags"); node1.add(one); node1.add(two); node1.add(three); node2.add(four); node2.add(five); node2.add(six); node3.add(seven); node3.add(eight); node4.add(nine); node4.add(ten); JTree tree = new JTree(node); for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } tree.putClientProperty("JTree.lineStyle", "Angled"); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION); tree.setRowHeight(25); frame.add(tree); frame.setSize(600,450); frame.setVisible(true); } }
输出
广告