Swing之JTree篇:在树节点前增加JCheckBox控件

2024-01-04 02:48

本文主要是介绍Swing之JTree篇:在树节点前增加JCheckBox控件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在做Swing开发的时候可能经常会遇到类似的案例,关键还是需要实现TreeCellRenderer接口,重写getTreeCellRendererComponent方法

 

import java.awt.BorderLayout;   
import java.awt.Color;   
import java.awt.Component;   
import java.awt.Dimension;   
import java.awt.Graphics;   
import java.awt.GridLayout;   
import java.awt.event.ActionEvent;   
import java.awt.event.ActionListener;   
import java.awt.event.MouseAdapter;   
import java.awt.event.MouseEvent;   
import java.awt.event.WindowAdapter;   
import java.awt.event.WindowEvent;   
import java.util.Enumeration;   import javax.swing.ButtonGroup;   
import javax.swing.Icon;   
import javax.swing.JButton;   
import javax.swing.JCheckBox;   
import javax.swing.JFrame;   
import javax.swing.JLabel;   
import javax.swing.JPanel;   
import javax.swing.JRadioButton;   
import javax.swing.JScrollPane;   
import javax.swing.JTextArea;   
import javax.swing.JTree;   
import javax.swing.UIManager;   
import javax.swing.border.TitledBorder;   
import javax.swing.plaf.ColorUIResource;   
import javax.swing.tree.DefaultMutableTreeNode;   
import javax.swing.tree.DefaultTreeModel;   
import javax.swing.tree.TreeCellRenderer;   
import javax.swing.tree.TreeNode;   
import javax.swing.tree.TreePath;   
import javax.swing.tree.TreeSelectionModel;   public class CheckNodeTreeExample extends JFrame {   public CheckNodeTreeExample() {   super("CheckNode TreeExample");   String[] strs = {"swing",     // 0   "platf",     // 1   "basic",     // 2   "metal",     // 3   "JTree"};    // 4   CheckNode[] nodes = new CheckNode[strs.length];   for (int i=0;i<strs.length;i++) {   nodes[i] = new CheckNode(strs[i]);   }   nodes[0].add(nodes[1]);   nodes[1].add(nodes[2]);   nodes[1].add(nodes[3]);   nodes[0].add(nodes[4]);   nodes[3].setSelected(true);   JTree tree = new JTree( nodes[0] );   tree.setCellRenderer(new CheckRenderer());   tree.getSelectionModel().setSelectionMode(   TreeSelectionModel.SINGLE_TREE_SELECTION   );   tree.putClientProperty("JTree.lineStyle", "Angled");   tree.addMouseListener(new NodeSelectionListener(tree));   JScrollPane sp = new JScrollPane(tree);   ModePanel mp = new ModePanel(nodes);   JTextArea textArea = new JTextArea(3,10);   JScrollPane textPanel = new JScrollPane(textArea);   JButton button = new JButton("print");   button.addActionListener(   new ButtonActionListener(nodes[0], textArea));   JPanel panel = new JPanel(new BorderLayout());   panel.add(mp,     BorderLayout.CENTER);   panel.add(button, BorderLayout.SOUTH);   getContentPane().add(sp,    BorderLayout.CENTER);   getContentPane().add(panel, BorderLayout.EAST);   getContentPane().add(textPanel, BorderLayout.SOUTH);   }   class NodeSelectionListener extends MouseAdapter {   JTree tree;   NodeSelectionListener(JTree tree) {   this.tree = tree;   }   public void mouseClicked(MouseEvent e) {   int x = e.getX();   int y = e.getY();   int row = tree.getRowForLocation(x, y);   TreePath  path = tree.getPathForRow(row);   //TreePath  path = tree.getSelectionPath();   if (path != null) {   CheckNode node = (CheckNode)path.getLastPathComponent();   boolean isSelected = ! (node.isSelected());   node.setSelected(isSelected);   if (node.getSelectionMode() == CheckNode.DIG_IN_SELECTION) {   if ( isSelected) {   tree.expandPath(path);   } else {   tree.collapsePath(path);   }   }   ((DefaultTreeModel) tree.getModel()).nodeChanged(node);   // I need revalidate if node is root.  but why?   if (row == 0) {   tree.revalidate();   tree.repaint();   }   }   }   }   class ModePanel extends JPanel implements ActionListener {   CheckNode[] nodes;   JRadioButton b_single, b_dig_in;   ModePanel(CheckNode[] nodes) {   this.nodes = nodes;   setLayout(new GridLayout(2, 1));   setBorder(new TitledBorder("Check Mode"));   ButtonGroup group = new ButtonGroup();   add(b_dig_in = new JRadioButton("DIG_IN  "));   add(b_single = new JRadioButton("SINGLE  "));   group.add(b_dig_in);   group.add(b_single);   b_dig_in.addActionListener(this);   b_single.addActionListener(this);   b_dig_in.setSelected(true);   }   public void actionPerformed(ActionEvent e) {   int mode;   if (b_single == e.getSource()) {   mode = CheckNode.SINGLE_SELECTION;   } else {   mode = CheckNode.DIG_IN_SELECTION;   }   for (int i = 0; i < nodes.length; i++) {   nodes[i].setSelectionMode(mode);   }   }   }   class ButtonActionListener implements ActionListener {   CheckNode root;   JTextArea textArea;   ButtonActionListener(final CheckNode root, final JTextArea textArea) {   this.root = root;   this.textArea = textArea;   }   public void actionPerformed(ActionEvent ev) {   Enumeration e = root.breadthFirstEnumeration();   while (e.hasMoreElements()) {   CheckNode node = (CheckNode) e.nextElement();   if (node.isSelected()) {   TreeNode[] nodes = node.getPath();   textArea.append("/n" + nodes[0].toString());   for (int i = 1; i < nodes.length; i++) {   textArea.append("/" + nodes[i].toString());   }   }   }   }   }   public static void main(String args[]) {   
//    try {   
//        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");   
//    } catch (Exception evt) {}   CheckNodeTreeExample frame = new CheckNodeTreeExample();   frame.addWindowListener(new WindowAdapter() {   public void windowClosing(WindowEvent e) {   System.exit(0);   }   });   frame.setSize(300, 200);   frame.setVisible(true);   }   
}   class CheckRenderer extends JPanel implements TreeCellRenderer {   protected JCheckBox check;   protected TreeLabel label;   public CheckRenderer() {   setLayout(null);   add(check = new JCheckBox());   add(label = new TreeLabel());   check.setBackground(UIManager.getColor("Tree.textBackground"));   label.setForeground(UIManager.getColor("Tree.textForeground"));   }   public Component getTreeCellRendererComponent(JTree tree, Object value,   boolean isSelected, boolean expanded, boolean leaf, int row,   boolean hasFocus) {   String stringValue = tree.convertValueToText(value, isSelected,   expanded, leaf, row, hasFocus);   setEnabled(tree.isEnabled());   check.setSelected(((CheckNode) value).isSelected());   label.setFont(tree.getFont());   label.setText(stringValue);   label.setSelected(isSelected);   label.setFocus(hasFocus);   if (leaf) {   label.setIcon(UIManager.getIcon("Tree.leafIcon"));   } else if (expanded) {   label.setIcon(UIManager.getIcon("Tree.openIcon"));   } else {   label.setIcon(UIManager.getIcon("Tree.closedIcon"));   }   return this;   }   public Dimension getPreferredSize() {   Dimension d_check = check.getPreferredSize();   Dimension d_label = label.getPreferredSize();   return new Dimension(d_check.width + d_label.width,   (d_check.height < d_label.height ? d_label.height   : d_check.height));   }   public void doLayout() {   Dimension d_check = check.getPreferredSize();   Dimension d_label = label.getPreferredSize();   int y_check = 0;   int y_label = 0;   if (d_check.height < d_label.height) {   y_check = (d_label.height - d_check.height) / 2;   } else {   y_label = (d_check.height - d_label.height) / 2;   }   check.setLocation(0, y_check);   check.setBounds(0, y_check, d_check.width, d_check.height);   label.setLocation(d_check.width, y_label);   label.setBounds(d_check.width, y_label, d_label.width, d_label.height);   }   public void setBackground(Color color) {   if (color instanceof ColorUIResource)   color = null;   super.setBackground(color);   }   public class TreeLabel extends JLabel {   boolean isSelected;   boolean hasFocus;   public TreeLabel() {   }   public void setBackground(Color color) {   if (color instanceof ColorUIResource)   color = null;   super.setBackground(color);   }   public void paint(Graphics g) {   String str;   if ((str = getText()) != null) {   if (0 < str.length()) {   if (isSelected) {   g.setColor(UIManager   .getColor("Tree.selectionBackground"));   } else {   g.setColor(UIManager.getColor("Tree.textBackground"));   }   Dimension d = getPreferredSize();   int imageOffset = 0;   Icon currentI = getIcon();   if (currentI != null) {   imageOffset = currentI.getIconWidth()   + Math.max(0, getIconTextGap() - 1);   }   g.fillRect(imageOffset, 0, d.width - 1 - imageOffset,   d.height);   if (hasFocus) {   g.setColor(UIManager   .getColor("Tree.selectionBorderColor"));   g.drawRect(imageOffset, 0, d.width - 1 - imageOffset,   d.height - 1);   }   }   }   super.paint(g);   }   public Dimension getPreferredSize() {   Dimension retDimension = super.getPreferredSize();   if (retDimension != null) {   retDimension = new Dimension(retDimension.width + 3,   retDimension.height);   }   return retDimension;   }   public void setSelected(boolean isSelected) {   this.isSelected = isSelected;   }   public void setFocus(boolean hasFocus) {   this.hasFocus = hasFocus;   }   }   
}   class CheckNode extends DefaultMutableTreeNode {   public final static int SINGLE_SELECTION = 0;   public final static int DIG_IN_SELECTION = 4;   protected int selectionMode;   protected boolean isSelected;   public CheckNode() {   this(null);   }   public CheckNode(Object userObject) {   this(userObject, true, false);   }   public CheckNode(Object userObject, boolean allowsChildren,   boolean isSelected) {   super(userObject, allowsChildren);   this.isSelected = isSelected;   setSelectionMode(DIG_IN_SELECTION);   }   public void setSelectionMode(int mode) {   selectionMode = mode;   }   public int getSelectionMode() {   return selectionMode;   }   public void setSelected(boolean isSelected) {   this.isSelected = isSelected;   if ((selectionMode == DIG_IN_SELECTION) && (children != null)) {   Enumeration e = children.elements();   while (e.hasMoreElements()) {   CheckNode node = (CheckNode) e.nextElement();   node.setSelected(isSelected);   }   }   }   public boolean isSelected() {   return isSelected;   }   
}  


 

这篇关于Swing之JTree篇:在树节点前增加JCheckBox控件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/567933

相关文章

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

day-51 合并零之间的节点

思路 直接遍历链表即可,遇到val=0跳过,val非零则加在一起,最后返回即可 解题过程 返回链表可以有头结点,方便插入,返回head.next Code /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}*

Java 创建图形用户界面(GUI)入门指南(Swing库 JFrame 类)概述

概述 基本概念 Java Swing 的架构 Java Swing 是一个为 Java 设计的 GUI 工具包,是 JAVA 基础类的一部分,基于 Java AWT 构建,提供了一系列轻量级、可定制的图形用户界面(GUI)组件。 与 AWT 相比,Swing 提供了许多比 AWT 更好的屏幕显示元素,更加灵活和可定制,具有更好的跨平台性能。 组件和容器 Java Swing 提供了许多

EMLOG程序单页友链和标签增加美化

单页友联效果图: 标签页面效果图: 源码介绍 EMLOG单页友情链接和TAG标签,友链单页文件代码main{width: 58%;是设置宽度 自己把设置成与您的网站宽度一样,如果自适应就填写100%,TAG文件不用修改 安装方法:把Links.php和tag.php上传到网站根目录即可,访问 域名/Links.php、域名/tag.php 所有模板适用,代码就不粘贴出来,已经打

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

lvgl8.3.6 控件垂直布局 label控件在image控件的下方显示

在使用 LVGL 8.3.6 创建一个垂直布局,其中 label 控件位于 image 控件下方,你可以使用 lv_obj_set_flex_flow 来设置布局为垂直,并确保 label 控件在 image 控件后添加。这里是如何步骤性地实现它的一个基本示例: 创建父容器:首先创建一个容器对象,该对象将作为布局的基础。设置容器为垂直布局:使用 lv_obj_set_flex_flow 设置容器

JS和jQuery获取节点的兄弟,父级,子级元素

原文转自http://blog.csdn.net/duanshuyong/article/details/7562423 先说一下JS的获取方法,其要比JQUERY的方法麻烦很多,后面以JQUERY的方法作对比。 JS的方法会比JQUERY麻烦很多,主要则是因为FF浏览器,FF浏览器会把你的换行也当最DOM元素。 <div id="test"><div></div><div></div

小程序button控件上下边框的显示和隐藏

问题 想使用button自带的loading图标功能,但又不需要button显示边框线 button控件有一条淡灰色的边框,在控件上了样式 border:none; 无法让button边框隐藏 代码如下: <button class="btn">.btn{border:none; /*一般使用这个就是可以去掉边框了*/} 解决方案 发现button控件有一个伪元素(::after

MFC中Spin Control控件使用,同时数据在Edit Control中显示

实现mfc spin control 上下滚动,只需捕捉spin control 的 UDN_DELTAPOD 消息,如下:  OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult) {  LPNMUPDOWN pNMUpDown = reinterpret_cast(pNMHDR);  // TODO: 在此添加控件通知处理程序代码    if

驱动(RK3588S)第七课时:单节点设备树

目录 需求一、设备树的概念1、设备树的后缀名:2、设备树的语法格式3、设备树的属性(重要)4、设备树格式举例 二、设备树所用函数1、如何在内核层种获取设备树节点:2、从设备树上获取 gpio 口的属性3、获取节点上的属性只针对于字符串属性的4、函数读取 np 结点中的 propname 属性的值,并将读取到的 u32 类型的值保存在 out_value 指向的内存中,函数的返回值表示读取到的