Este artículo comparte el código específico que se muestra en la casilla de verificación Java JTree JCheckbox Tree para su referencia. El contenido específico es el siguiente
1.Checktreemanager.java
Public Class CheckTreManager extiende Mouseadapter implementa TreeSelectionListener {private checktreeSelectionModel selectionModel = null; // private jtree tree = new Jtree (); árbol de jtree privado = nulo; int hotspot = new JCheckbox (). getPreferredSize (). Width; Public checktreemanager (jtree tree) {this.tree = tree; selectionModel = new ChecktreeSelectionModel (tree.getModel ()); Tree.setCellRenderer (nuevo checktreeCellRenderer (tree.getCellRenderer (), selectionModel)); árbol.addmouselistener (esto); // Selección de escucha del mouseModel.addtreeSelectionListener (esto); // Selección de árbol escucha} public void mouseClicked (mousevent me) {treePath Path = tree.getPathForLocation (me.getx (), me.gety ()); if (ruta == nulo) return; if (me.getx ()> tree.getPathBounds (ruta) .x+hotspot) return; boolean seleccionado = selectionModel.ispathSelected (ruta, verdadero); selectionModel.removetreeselectionListener (this); intente {if (seleccionado) selectionModel.removeselectionPath (ruta); else SelectionModel.addselectionPath (ruta); } finalmente {selectionModel.addtreeSelectionListener (this); Tree.TreedidChange (); }} public checktreeSelectionModel getSelectionModel () {return SelectionModel; } public void valueChanged (TreeSelectionEvent e) {tree.treedidchange (); }} 2.ChecktreeSelectionModel.java
clase pública checktreeSelectionModel extiende predeterminando la elección de selección {modelo privado de treemodel; Public checktreeSelectionModel (modelo TreeModel) {this.model = modelo; setSelectionMode (TreeSelectionModel.Discontigua_tree_Selection); } // prueba si hay algún nodo no seleccionado en el subárbol de la ruta dada pública boolean ispartialselected (treePath ruta) {if (ispathSelected (ruta, true)) return false; TreePath [] selectionPaths = getSelectionPaths (); if (selectionPaths == null) return false; for (int j = 0; j <selectionPaths.length; j ++) {if (isDescendant (selectionPaths [j], ruta)) return true; } return false; } // dice si se selecciona la ruta dada. // Si Dig es verdadero, se supone que se selecciona una ruta, si // se selecciona uno de sus antepasados. Public boolean ispathSelected (treePath ruta, boolean dig) {if (! dig) return super.IspathSelected (ruta); while (ruta! = null &&! super.ispathselected (ruta)) ruta = rath.getParentPath (); ruta de retorno! = nulo; } // es Path1 Descendiente de Path2 Private Boolean IsDescendant (TreePath Path1, TreePath Path2) {Objus obj1 [] = Path1.getPath (); Objero obj2 [] = path2.getPath (); para (int i = 0; i <obj2.length; i ++) {if (obj1 [i]! = obj2 [i]) return false; } return verdadero; } public void setSelectionPaths (TreePath [] PPaths) {tire nueva no compatible conperationException ("¡No implementado todavía!"); } public void addSelectionPaths (TreePath [] rutas) {// Unselectar todos los descendientes de las rutas [] para (int i = 0; i <raths.length; i ++) {treePath ruta = rutas [i]; TreePath [] selectionPaths = getSelectionPaths (); if (SelectionPaths == NULL) Break; ArrayList toberemoved = new ArrayList (); for (int j = 0; j <selectionPaths.length; j ++) {if (isDescendant (selectionPaths [j], ruta)) toberemoved.add (selectionPaths [j]); } super.removeselectionPaths ((treePath []) toberemoved.toarray (new TreePath [0])); } // Si todos los hermanos se seleccionan, no seleccione y seleccione Parents recursivamente // Otrowize simplemente seleccione esa ruta. para (int i = 0; i <raths.length; i ++) {treePath ruta = ruta [i]; TreePath temp = null; while (aresiblingsselected (ruta)) {temp = ruta; if (path.getParentPath () == NULL) Break; ruta = Path.getParentPath (); } if (temp! = null) {if (temp.getParentPath ()! = null) addSelectionPath (temp.getParentPath ()); else {if (! isselectionEmpty ()) eliminar la selección de capitán (getSelectionPaths ()); super.addselectionPath (new TreePath [] {temp}); }} else super.addselectionPaths (new TreePath [] {ruta}); }} // dice si se seleccionan todos los hermanos de la ruta dada. aresiblingsselected privado booleano (ruta treePath) {treePath parent = path.getParentPath (); if (parent == null) return true; Objeto nodo = path.getLastPathComponent (); Objeto parentNode = parent.getLastPathComponent (); int ChildCount = Model.getChildCount (ParentNode); for (int i = 0; i <childCount; i ++) {object childNode = model.getChild (parentNode, i); if (childNode == nodo) continuar; if (! ispathSelected (parent.pathbyaddingchild (childnode))) return false; } return verdadero; } public void eliminar electionPath (treePath [] rutas) {para (int i = 0; i <raths.length; i ++) {treePath ruta = ruta [i]; if (path.getPathCount () == 1) super.removeselectionPaths (new TreePath [] {ruta}); else toggLerEmoveselection (ruta); }} // Si se selecciona algún nodo de antepasado de la ruta dada, entonces no seleccione // y seleccione a todos sus descendientes, excepto la ruta y los descendientes dados. // de lo contrario, simplemente no seleccione la ruta dada, void private toggLerEmoveselection (ruta treePath) {panteta stack = new stack (); TreePath Parent = Path.getParentPath (); while (parent! = null &&! ispathselected (parent)) {stack.push (parent); parent = parent.getParentPath (); } if (parent! = null) stack.push (parent); else {super.removeselectionPath (new TreePath [] {ruta}); devolver; } while (! stack.isEmpty ()) {treePath temp = (treePath) stack.pop (); TreePath Peekpath = stack.isempty ()? camino: (treePath) stack.peek (); Objeto nodo = temp.getLastPathComponent (); Object Peeknode = Peekpath.getLastPathComponent (); int ChildCount = Model.getChildCount (nodo); for (int i = 0; i <childCount; i ++) {object childNode = model.getChild (nodo, i); if (childNode! = Peeknode) super.addselectionPaths (new TreePath [] {temp.pathbyaddingChild (childNode)}); }} super.removeselectionPath (new TreePath [] {Parent}); }} 3.Checktreecellrenderer .Java
clase pública checktreecellrenderer extiende jpanel implementa treecellrenderer {private checktreeSelectionModel SelectionModel; Delegado privado Treecellrenderer; // casilla de verificación privada TristateCheckBox = new TristateCheckBox (); stives jcheckbox chechbox = new JCheckbox (); Public checkTreeCellrenderer (TreeCellrenderer Delegate, checktreeSelectionModel SelectionModel) {this.delegate = delegate; this.selectionModel = selectionModel; setLayout (new BorderLayout ()); setOpaque (falso); checkbox.setOpAque (falso); } componente público getTreeCellrendererComponent (árbol JTree, valor de objeto, boolean seleccionado, booleano expandido, hoja booleana, int row, boolean Hasfocus) {componente renderer = delegate.gettreecellrendererComponent (árbol, valor, seleccionado, expandido, hoja, fila, hasfocus); TreePath Path = tree.getPathForrow (fila); if (path! = null) {system.out.println (ruta); if (selectionModel.ispathSelected (ruta, true)) checkbox.setselected (true); else {System.out.println (SelectionModel.IsPartialselected (ruta)); checkbox.setselected (selectionModel.IsPartialselected (ruta)? Verdadero: falso); }} removeAll (); agregar (casilla de verificación, borderLayout.west); agregar (renderer, borderLayout.center); devolver esto; }} 4. Uso
Checktreemanager checktreemanager = nuevo checktreemanager (jtree);
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.