Este artigo compartilha o código específico exibido na caixa de seleção Java Jtree Jcheckbox Tree para sua referência. O conteúdo específico é o seguinte
1.Checktreemanager.java
classe pública checktreemanager estende mouseAdApter implementa TreeSelectionListener {Private CheckTreeSelectionModel SelectionModel = NULL; // private jtree árvore = novo jtree (); Árvore Jtree privada = NULL; int hotspot = new jCheckBox (). getPreferredSize (). Largura; public checktreemanager (JTree Tree) {this.tree = árvore; SelectionModel = new CheckTreeSelectionModel (Tree.getModel ()); Tree.setCellRenderer (New CheckTreeCellRenderer (Tree.getCellRenderer (), SelectionModel)); Tree.AddmouseListener (isto); // mouse escuta seleçãomodel.addtreeSelectionListener (isto); // seleção de árvores escuta} public void mouseclicked (mouseevent me) {Treepath path = Tree.getPathForLocation (me.getx (), me.gety ()); if (path == null) retornar; if (me.getx ()> árvore.getPhPlBounds (path) .x+hotspot) retornar; booleano selecionado = seleçãoModel.ispathSelected (caminho, true); SelectionModel.RemoveTreeSelectionListener (isto); tente {if (selecionado) SelectionModel.RemoveSelectionPath (caminho); caso contrário, seleçãomodel.addSelectionPath (caminho); } finalmente {SelectionModel.addtreeSelectionListener (this); árvore.TreedIdChange (); }} public checkTreeSelectionModel getSelectionModel () {return SelectionModel; } public void valuechanged (TreeSelectionEvent e) {Tree.TreedIdChange (); }} 2.CheckTreeSelectionModel.java
classe pública CheckTreeSelectionModel estende o DefaultTreeSelectionModel {Modelo Treemodel Private; public checktreeSelectionModel (modelo Treemodel) {this.model = Model; setSelectionMode (TreeSelectionModel.DISCONTIGOUSE_TREE_SELECTION); } // Testes se existe algum nó não selecionado na subárvore do caminho determinado Public Boolean isPartiallySelected (Treepath Path) {if (isPathSelected (path, true)) retornar false; Treepath [] seleçãopaths = getSelectionPaths (); if (SelectionPaths == NULL) retorna false; for (int j = 0; j <seleçãopaths.length; j ++) {if (isDescendente (seleçãopaths [j], path)) retorna true; } retornar false; } // informa se o caminho fornecido está selecionado. // Se o DIG for verdadeiro, é considerado um caminho selecionado, se // um de seu ancestral for selecionado. public boolean isPathSelected (Treepath Path, Boolean Dig) {if (! Dig) retorna super.ispathSelected (caminho); while (caminho! caminho de retorno! = nulo; } // é PATH1 Descendente de Path2 Private Boolean IsDescendente (Treepath Path1, Treepath Path2) {objeto obj1 [] = path1.getPath (); Objeto obj2 [] = path2.getPath (); for (int i = 0; i <obj2.Length; i ++) {if (obj1 [i]! = obj2 [i]) retorna false; } retornar true; } public void setSelectionPaths (Treepath [] ppaths) {lança novo UnsupportEdOperationException ("ainda não implementado !!!"); } public void addSelectionPaths (Treepath [] caminhos) {// Unselecte todos os descendentes de caminhos [] para (int i = 0; i <paths.length; i ++) {Treepath Path = Paths [i]; Treepath [] seleçãopaths = getSelectionPaths (); if (SelectionPaths == NULL) quebra; Arraylist toBeemoved = new ArrayList (); for (int j = 0; j <seleçãopaths.length; j ++) {if (isDesCinging (SelectionPaths [j], caminho)) toberemoved.add (seleçãopaths [j]); } super.removeSelectionPaths ((Treepath []) toberemoved.toArray (New Treepath [0])); } // Se todos os irmãos forem selecionados, desastre -os e selecione os pais recursivamente // Otherwize, basta selecionar esse caminho. for (int i = 0; i <paths.length; i ++) {Treepath Path = Paths [i]; Treepath temp = nulo; while (AresiBlingSSelected (Path)) {temp = Path; if (path.getParentPath () == null) quebra; caminho = path.getParentPath (); } if (temp! = null) {if (temp.getParentPath ()! = null) addSelectionPath (temp.getParentPath ()); else {if (! isSelectionEmpty ()) removeselectionPaths (getSelectionPaths ()); Super.addSelectionPaths (novo Treepath [] {temp}); }} else Super.addSelectionPaths (new Treepath [] {Path}); }} // informa se todos os irmãos do caminho determinado são selecionados. private boolean AresiblingSselected (Treepath Path) {Treepath Parent = Path.getParentPath (); if (pai == NULL) retorna true; Nó do objeto = path.getLastPathComponent (); Objeto parentnode = parent.getLastPathComponent (); int infantcount = model.getChildCount (parentnode); for (int i = 0; i <ChildCount; i ++) {object ChildNode = Model.getChild (parentNode, i); if (ChildNode == Node) continue; if (! ispathSelected (parent.pathbyaddingchild (ChildNode))) retorna false; } retornar true; } public void removeselectionPaths (Treepath [] caminhos) {for (int i = 0; i <paths.length; i ++) {Treepath Path = Caminhos [i]; if (path.getPathCount () == 1) super.remeSelectionPaths (new Treepath [] {path}); else ToggleRemoveSelection (caminho); }} // Se qualquer nó ancestral do caminho determinado for selecionado, ilustre -o // e a seleção de todos os seus descendentes, exceto o caminho e os descendentes. //, caso contrário, basta selecionar o caminho que o caminho privado de vazio ToggleRemeSelection (caminho treepath) {pilha pilha = new Stack (); Treepath pai = path.getParentPath (); while (pai! = null &&! ispathSelected (pai)) {staack.push (pai); pai = parent.getParentPath (); } if (pai! = null) pilha.push (pai); else {super.RemoveSelectionPaths (new Treepath [] {Path}); retornar; } while (! Stack.isEmpty ()) {Treepath temp = (treepath) Stack.pop (); Treepath peekpath = Stack.isempty ()? Caminho: (Treepath) Stack.peek (); Nó do objeto = temp.getLastPathComponent (); Objeto peeknode = peekpath.getLastPathComponent (); int infantcount = model.getChildCount (nó); for (int i = 0; i <ChildCount; i ++) {object ChildNode = Model.getChild (nó, i); if (ChildNode! = PeekNode) super.addSelectionPaths (new Treepath [] {temp.PathbyaddingChild (ChildNode)}); }} super.removeSelectionPaths (new Treepath [] {Parent}); }} 3.CHECKTREECELLRENDERER .Java
classe pública checktreeCellRenderer estende o jpanel implementa TreeCellRenderer {Private CheckTreeSelectionModel SelectionModel; Delegado privado de TreeCellRenderer; // Caixa de seleção Private TristateCheckBox = new TristateCheckBox (); caixa de seleção privada jcheckbox = new jcheckbox (); public checktreeCellRenderer (delegado de TreeCellRenderer, checkTreesElectionModel SelectionModel) {this.delegate = delegado; this.SelectionModel = seleçãoModel; setLayout (new BorderLayout ()); Setopaque (falso); Caixa de seleção.SETOPAQUE (FALSE); } componente público gettreeCellRendeRComponent (árvore jTree, valor do objeto, booleano selecionado, expandido booleano, folha booleana, int linha, boolean hasfocus) {renderizador de componente = delegate.getTreeCellRenderRomConen (Tree, valor, selecionado, expandido, expandido, row, row, hasfocus); Treepath Path = Tree.getPathForrow (linha); if (path! = null) {System.out.println (caminho); if (SelectionModel.ISPATHSELECT (PATH, TRUE)) Caixa de seleção.SetSElected (true); else {System.out.println (seleçãoModel.iscartiallySelected (Path)); Caixa de seleção.SetSelectected (SelectionModel.ISPARTALIALIZADA (PATH)? TRUE: FALSE); }} removeall (); add (caixa de seleção, borderlayout.west); add (renderizador, borderlayout.center); devolver isso; }} 4. Uso
Checktreemanager checktreemanager = new checktreemanager (jTree);
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.