java JTree JCheckBox树复选框详解

本文实例为大家分享了java JTree JCheckBox树复选框展示的具体代码,供大家参考,具体内容如下

1.CheckTreeManager.java

public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener
{ 

  private CheckTreeSelectionModel selectionModel = null; 

// private JTree tree = new JTree();
  private JTree tree = null; 

  int hotspot = new JCheckBox().getPreferredSize().width; 

  public CheckTreeManager(JTree tree)
  {
   this.tree = tree;
   selectionModel = new CheckTreeSelectionModel(tree.getModel());
   tree.setCellRenderer(new CheckTreeCellRenderer(tree.getCellRenderer(), selectionModel));
   tree.addMouseListener(this); //鼠标监听
   selectionModel.addTreeSelectionListener(this); //树选择监听
  } 

  public void mouseClicked(MouseEvent me)
  {
   TreePath path = tree.getPathForLocation(me.getX(), me.getY());
   if(path==null)
    return;
   if(me.getX()>tree.getPathBounds(path).x+hotspot)
    return; 

   boolean selected = selectionModel.isPathSelected(path, true);
   selectionModel.removeTreeSelectionListener(this); 

   try
   {
    if(selected)
     selectionModel.removeSelectionPath(path);
    else
     selectionModel.addSelectionPath(path);
   }
   finally
   {
    selectionModel.addTreeSelectionListener(this);
    tree.treeDidChange();
   }
  } 

  public CheckTreeSelectionModel getSelectionModel()
  {
   return selectionModel;
  } 

  public void valueChanged(TreeSelectionEvent e)
  {
   tree.treeDidChange();
  } 

}

2.CheckTreeSelectionModel.java

public class CheckTreeSelectionModel extends DefaultTreeSelectionModel
{
  private TreeModel model; 

  public CheckTreeSelectionModel(TreeModel model)
  {
   this.model = model;
   setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
  } 

  // tests whether there is any unselected node in the subtree of given path
  public boolean isPartiallySelected(TreePath path){
   if(isPathSelected(path, true))
    return false;
   TreePath[] selectionPaths = getSelectionPaths();
   if(selectionPaths==null)
    return false;
   for(int j = 0; j<selectionPaths.length; j++)
   {
    if(isDescendant(selectionPaths[j], path))
     return true;
   }
   return false;
  } 

  // tells whether given path is selected.
  // if dig is true, then a path is assumed to be selected, if
  // one of its ancestor is selected.
  public boolean isPathSelected(TreePath path, boolean dig)
  {
   if(!dig)
    return super.isPathSelected(path);
   while(path!=null && !super.isPathSelected(path))
    path = path.getParentPath();
   return path!=null;
  } 

  // is path1 descendant of path2
  private boolean isDescendant(TreePath path1, TreePath path2)
  {
   Object obj1[] = path1.getPath();
   Object obj2[] = path2.getPath();
   for(int i = 0; i<obj2.length; i++)
   {
    if(obj1[i]!=obj2[i])
     return false;
   }
   return true;
  } 

  public void setSelectionPaths(TreePath[] pPaths)
  {
   throw new UnsupportedOperationException("not implemented yet!!!");
  } 

  public void addSelectionPaths(TreePath[] paths)
  {
   // unselect all descendants of paths[]
   for(int i = 0; i<paths.length; i++){
    TreePath path = paths[i];
    TreePath[] selectionPaths = getSelectionPaths();
    if(selectionPaths==null)
     break;
    ArrayList toBeRemoved = new ArrayList();
    for(int j = 0; j<selectionPaths.length; j++)
    {
     if(isDescendant(selectionPaths[j], path))
      toBeRemoved.add(selectionPaths[j]);
    }
    super.removeSelectionPaths((TreePath[])toBeRemoved.toArray(new TreePath[0]));
   } 

   // if all siblings are selected then unselect them and select parent recursively
   // otherwize just select that path.
   for(int i = 0; i<paths.length; i++)
   {
    TreePath path = paths[i];
    TreePath temp = null;
    while(areSiblingsSelected(path))
    {
     temp = path;
     if(path.getParentPath()==null)
      break;
     path = path.getParentPath();
    }
    if(temp!=null)
    {
     if(temp.getParentPath()!=null)
      addSelectionPath(temp.getParentPath());
     else
     {
      if(!isSelectionEmpty())
       removeSelectionPaths(getSelectionPaths());
      super.addSelectionPaths(new TreePath[]{temp});
     }
    }
    else
     super.addSelectionPaths(new TreePath[]{ path});
   }
  } 

  // tells whether all siblings of given path are selected.
  private boolean areSiblingsSelected(TreePath path)
  {
   TreePath parent = path.getParentPath();
   if(parent==null)
    return true;
   Object node = path.getLastPathComponent();
   Object parentNode = parent.getLastPathComponent(); 

   int childCount = 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)))
     return false;
   }
   return true;
  } 

  public void removeSelectionPaths(TreePath[] paths)
  {
   for(int i = 0; i<paths.length; i++){
    TreePath path = paths[i];
    if(path.getPathCount()==1)
     super.removeSelectionPaths(new TreePath[]{ path});
    else
     toggleRemoveSelection(path);
   }
  } 

  // if any ancestor node of given path is selected then unselect it
  // and selection all its descendants except given path and descendants.
  // otherwise just unselect the given path
  private void toggleRemoveSelection(TreePath path)
  {
   Stack 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.removeSelectionPaths(new TreePath[]{path});
    return;
   } 

   while(!stack.isEmpty())
   {
    TreePath temp = (TreePath)stack.pop();
    TreePath peekPath = stack.isEmpty() ? path : (TreePath)stack.peek();
    Object node = temp.getLastPathComponent();
    Object peekNode = peekPath.getLastPathComponent();
    int childCount = model.getChildCount(node);
    for(int i = 0; i<childCount; i++){
     Object childNode = model.getChild(node, i);
     if(childNode!=peekNode)
      super.addSelectionPaths(new TreePath[]{temp.pathByAddingChild(childNode)});
    }
   }
   super.removeSelectionPaths(new TreePath[]{parent});
  } 

}

3.CheckTreeCellRenderer .java

public class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer
{
 private CheckTreeSelectionModel selectionModel;
 private TreeCellRenderer delegate;
// private TristateCheckBox checkBox = new TristateCheckBox();
 private JCheckBox checkBox = new JCheckBox(); 

 public CheckTreeCellRenderer(TreeCellRenderer delegate, CheckTreeSelectionModel selectionModel){
  this.delegate = delegate;
  this.selectionModel = selectionModel;
  setLayout(new BorderLayout());
  setOpaque(false);
  checkBox.setOpaque(false);
 } 

 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
  Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); 

  TreePath path = tree.getPathForRow(row);
  if(path!=null)
  {
   System.out.println(path);
   if(selectionModel.isPathSelected(path, true))
    checkBox.setSelected(true);
   else
   {
    System.out.println(selectionModel.isPartiallySelected(path));
    checkBox.setSelected(selectionModel.isPartiallySelected(path) ? true : false);
   }
  }
  removeAll();
  add(checkBox, BorderLayout.WEST);
  add(renderer, BorderLayout.CENTER);
  return this;
 }
}

4.用法

CheckTreeManager checkTreeManager = new CheckTreeManager(jTree);  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • java通过复选框控件数组实现添加多个复选框控件示例分享

    思路如下: 创建JPanel面板对象:使用JPanel类的setLayout(0,4)方法设置网格布局管理器,即列数为4,行数自动调节:创建一个字符串型一维数组作为控件文本数组:创建一个JCheckBox型一维数组作为控件数组:使用for循环遍历控件数组,初始化数组中的复选框组件,使用JPanel类的add()方法把数组元素(即每个复选框)添加到面板中.代码如下: 复制代码 代码如下: package cn.edu.xidian.crytoll; import java.awt.BorderLa

  • Java Swing组件复选框JCheckBox用法示例

    本文实例讲述了Java Swing组件复选框JCheckBox用法.分享给大家供大家参考,具体如下: JCheckBox是Swing中的复选框.所谓复选框就是指,可以同时存在多个这样的控件,它们可以有多个处于被选中状态.对于每一个复选框而言,它只有选中和未选中两种状态. JCheckBox的常用方法如下图所示: 可以为它添加ActionListener对象来响应事件. 使用demo如下: JCheckBoxDemo.java package awtDemo; import java.awt.Bo

  • Java带复选框的树(Java CheckBox Tree)实现和应用

    在使用Java Swing开发UI程序时,很有可能会遇到使用带复选框的树的需求,但是Java Swing并没有提供这个组件,因此如果你有这个需求,你就得自己动手实现带复选框的树. CheckBoxTree与JTree在两个层面上存在差异: 1.在模型层上,CheckBoxTree的每个结点需要一个成员来保存其是否被选中,但是JTree的结点则不需要. 2.在视图层上,CheckBoxTree的每个结点比JTree的结点多显示一个复选框. 既然存在两个差异,那么只要我们把这两个差异部分通过自己的实

  • java之swing实现复选框的方法

    本文实例讲述了java之swing实现复选框的方法.分享给大家供大家参考.具体如下: import java.awt.*; import javax.swing.*; import java.awt.event.*; public class test extends JApplet implements ItemListener{ JTextField jtf; public void init(){ Container contentPane = getContentPane(); cont

  • java JTree JCheckBox树复选框详解

    本文实例为大家分享了java JTree JCheckBox树复选框展示的具体代码,供大家参考,具体内容如下 1.CheckTreeManager.java public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener { private CheckTreeSelectionModel selectionModel = null; // private JTree tree = new JT

  • asp.net在Repeater嵌套的Repeater中使用复选框详解

    .aspx文件中: <%--顶层Repeater--%> <asp:Repeater ID="rptChannel" runat="server"> <itemtemplate> <br /><b><%# Eval("ChannelName")%></b> <%--嵌套的Repeater,指定使用后台创建的Releation来获取数据源--%> <

  • Java框架学习Struts2复选框实例代码

    复选框在Web开发中使用的非常多,现在我们通过struts2的复选框标签来实现一些在开发中经常遇到的问题. 先来看看这个标签的属性: 注:listKey相当于HTML中的value属性,这个值在和后台交互时才真正是我们在后台要使用的:listValue只是内容的显示而已. 案例1 用户选择了喜欢的课程,现在要对已经选择的课程进行修改,跳转到修改界面,然后回显已经勾选的课程. 用户已选课程界面: 点击按钮后进入课程修改界面: 注:在修改界面要对用户最初的选择进行回显. 代码实现!!!! 用户已选课

  • element的el-tree多选树(复选框)父子节点关联不关联

    属性check-strictly 官方文档提供属性check-strictly,在显示复选框的情况下,是否严格的遵循父子不互相关联的做法,默认为 false. 而此属性的意思是: 默认false,父子关联.有如下现象及问题: 1.当你通过函数设置勾选节点的时候,只要父节点被勾选子节点必会勾选上,即便设置勾选的list中无此子节点. 2.当你点击勾选复选框时候,若点击父节点,其下子节点全部统一跟随父节点变化:若点击子节点,子节点部分勾选时父节点处于半选状态,子节点全部勾选时父节点选中,子节点全部不

  • Java如何做带复选框的菜单实例代码

    说明:         上面是我用Java做的扫雷游戏,其中就用到了带复选框式的菜单,原来也是用JCheckBoxMenuItem做的,但发现实在是问题多多,后干脆就用普通的JMenuItem来做,效果也不错.实际上说穿了很简单,就是在菜单的文本上做文章,前面加上一个 √ 即可.通过比较文本内容来判断是显示选中还是未选中,前面加还是不加 √ ,同时其他的文本内容如何变化,就好像扫雷的难度,初级.中级.高级只能选中一个. 代码: package com.game.mine; import java

  • Java Swing JCheckBox复选框的实现方法

    1. 概述 官方JavaDocsApi:javax.swing.JCheckBox JCheckBox,复选框. JCheckBox 常用构造方法: // 无文本,默认未选中 JCheckBox() // 有文本,默认未选中 JCheckBox(String text) // 有文本,并指定是否选中 JCheckBox(String text, boolean selected) JCheckBox 常用方法: // 设置复选框的 文本.字体 和 字体颜色 void setText(String

随机推荐