Swing之JTree篇:设置树选中节点背景色

2024-01-04 02:48

本文主要是介绍Swing之JTree篇:设置树选中节点背景色,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这个例子通过实现TreeCellRenderer接口来改变选中节点背景色,对树节点操作很多都是实现这个接口。话不多说,通过例子来看效果
import java.awt.BorderLayout;   
import java.awt.Color;   
import java.awt.Component;   
import java.awt.Dimension;   
import java.awt.FontMetrics;   
import java.awt.event.WindowAdapter;   
import java.awt.event.WindowEvent;   
import java.io.BufferedReader;   
import java.io.IOException;   
import java.io.StringReader;   import javax.swing.BorderFactory;   
import javax.swing.Box;   
import javax.swing.BoxLayout;   
import javax.swing.JFrame;   
import javax.swing.JLabel;   
import javax.swing.JPanel;   
import javax.swing.JScrollPane;   
import javax.swing.JTextArea;   
import javax.swing.JTree;   
import javax.swing.SwingUtilities;   
import javax.swing.UIManager;   
import javax.swing.plaf.ColorUIResource;   
import javax.swing.tree.DefaultMutableTreeNode;   
import javax.swing.tree.TreeCellRenderer;   public class MultiLineTreeExample extends JFrame {   public MultiLineTreeExample() {   super("Multi-Line JTree Example");   String[] strs = { "swing", // 0   "package", // 1   "java.awt.swing/n" + "com.sun.java.swing", // 2   "javax.swing", // 3   "JTree" }; // 4   DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[strs.length];   for (int i = 0; i < strs.length; i++) {   nodes[i] = new DefaultMutableTreeNode(strs[i]);   }   nodes[0].add(nodes[1]);   nodes[1].add(nodes[2]);   nodes[1].add(nodes[3]);   nodes[0].add(nodes[4]);   JTree tree = new JTree(nodes[0]);   tree.setEditable(true);   tree.setCellRenderer(new MultiLineCellRenderer());   JScrollPane sp = new JScrollPane();   sp.getViewport().add(tree);   getContentPane().add(sp, BorderLayout.CENTER);   }   public static void main(String args[]) {   try {   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");   } catch (Exception evt) {}   MultiLineTreeExample frame = new MultiLineTreeExample();   frame.addWindowListener(new WindowAdapter() {   public void windowClosing(WindowEvent e) {   System.exit(0);   }   });   frame.setSize(300, 150);   frame.setVisible(true);   }   
}   
//实现接口   
class MultiLineCellRenderer extends JPanel implements TreeCellRenderer {   protected JLabel icon;   protected TreeTextArea text;   public MultiLineCellRenderer() {   setLayout(new BoxLayout(this, BoxLayout.X_AXIS));   icon = new JLabel() {   public void setBackground(Color color) {   if (color instanceof ColorUIResource)   color = null;   super.setBackground(color);   }   };   add(icon);   add(Box.createHorizontalStrut(4));   add(text = new TreeTextArea());   }   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());   text.setText(stringValue);   text.setSelect(isSelected);   text.setFocus(hasFocus);   if (leaf) {   icon.setIcon(UIManager.getIcon("Tree.leafIcon"));   } else if (expanded) {   icon.setIcon(UIManager.getIcon("Tree.openIcon"));   } else {   icon.setIcon(UIManager.getIcon("Tree.closedIcon"));   }   return this;   }   public Dimension getPreferredSize() {   Dimension iconD = icon.getPreferredSize();   Dimension textD = text.getPreferredSize();   int height = iconD.height < textD.height ? textD.height : iconD.height;   return new Dimension(iconD.width + textD.width, height);   }   public void setBackground(Color color) {   if (color instanceof ColorUIResource)   color = null;   super.setBackground(color);   }   class TreeTextArea extends JTextArea {   Dimension preferredSize;   TreeTextArea() {   setLineWrap(true);   setWrapStyleWord(true);   setOpaque(true);   this.setText("dasfasdfasdfadsfa");   }   public void setBackground(Color color) {   if (color instanceof ColorUIResource)   color = null;   super.setBackground(color);   }   public void setPreferredSize(Dimension d) {   if (d != null) {   preferredSize = d;   }   }   public Dimension getPreferredSize() {   return preferredSize;   }   public void setText(String str) {   FontMetrics fm = getToolkit().getFontMetrics(getFont());   BufferedReader br = new BufferedReader(new StringReader(str));   String line;   int maxWidth = 0, lines = 0;   try {   while ((line = br.readLine()) != null) {   int width = SwingUtilities.computeStringWidth(fm, line);   if (maxWidth < width) {   maxWidth = width;   }   lines++;   }   } catch (IOException ex) {   ex.printStackTrace();   }   lines = (lines < 1) ? 1 : lines;   int height = fm.getHeight() * lines;   setPreferredSize(new Dimension(maxWidth + 6, height));   super.setText(str);   }   void setSelect(boolean isSelected) {   Color bColor;   if (isSelected) {   bColor = UIManager.getColor("Tree.selectionBackground");   } else {   bColor = UIManager.getColor("Tree.textBackground");   }   super.setBackground(bColor);   }   void setFocus(boolean hasFocus) {   if (hasFocus) {   Color lineColor = UIManager   .getColor("Tree.selectionBorderColor");   setBorder(BorderFactory.createLineBorder(lineColor));   } else {   setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));   }   }   }   
}  
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;public class MultiLineTreeExample extends JFrame {public MultiLineTreeExample() {super("Multi-Line JTree Example");String[] strs = { "swing", // 0"package", // 1"java.awt.swing/n" + "com.sun.java.swing", // 2"javax.swing", // 3"JTree" }; // 4DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[strs.length];for (int i = 0; i < strs.length; i++) {nodes[i] = new DefaultMutableTreeNode(strs[i]);}nodes[0].add(nodes[1]);nodes[1].add(nodes[2]);nodes[1].add(nodes[3]);nodes[0].add(nodes[4]);JTree tree = new JTree(nodes[0]);tree.setEditable(true);tree.setCellRenderer(new MultiLineCellRenderer());JScrollPane sp = new JScrollPane();sp.getViewport().add(tree);getContentPane().add(sp, BorderLayout.CENTER);}public static void main(String args[]) {try {UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");} catch (Exception evt) {}MultiLineTreeExample frame = new MultiLineTreeExample();frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});frame.setSize(300, 150);frame.setVisible(true);}
}
//实现接口
class MultiLineCellRenderer extends JPanel implements TreeCellRenderer {protected JLabel icon;protected TreeTextArea text;public MultiLineCellRenderer() {setLayout(new BoxLayout(this, BoxLayout.X_AXIS));icon = new JLabel() {public void setBackground(Color color) {if (color instanceof ColorUIResource)color = null;super.setBackground(color);}};add(icon);add(Box.createHorizontalStrut(4));add(text = new TreeTextArea());}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());text.setText(stringValue);text.setSelect(isSelected);text.setFocus(hasFocus);if (leaf) {icon.setIcon(UIManager.getIcon("Tree.leafIcon"));} else if (expanded) {icon.setIcon(UIManager.getIcon("Tree.openIcon"));} else {icon.setIcon(UIManager.getIcon("Tree.closedIcon"));}return this;}public Dimension getPreferredSize() {Dimension iconD = icon.getPreferredSize();Dimension textD = text.getPreferredSize();int height = iconD.height < textD.height ? textD.height : iconD.height;return new Dimension(iconD.width + textD.width, height);}public void setBackground(Color color) {if (color instanceof ColorUIResource)color = null;super.setBackground(color);}class TreeTextArea extends JTextArea {Dimension preferredSize;TreeTextArea() {setLineWrap(true);setWrapStyleWord(true);setOpaque(true);this.setText("dasfasdfasdfadsfa");}public void setBackground(Color color) {if (color instanceof ColorUIResource)color = null;super.setBackground(color);}public void setPreferredSize(Dimension d) {if (d != null) {preferredSize = d;}}public Dimension getPreferredSize() {return preferredSize;}public void setText(String str) {FontMetrics fm = getToolkit().getFontMetrics(getFont());BufferedReader br = new BufferedReader(new StringReader(str));String line;int maxWidth = 0, lines = 0;try {while ((line = br.readLine()) != null) {int width = SwingUtilities.computeStringWidth(fm, line);if (maxWidth < width) {maxWidth = width;}lines++;}} catch (IOException ex) {ex.printStackTrace();}lines = (lines < 1) ? 1 : lines;int height = fm.getHeight() * lines;setPreferredSize(new Dimension(maxWidth + 6, height));super.setText(str);}void setSelect(boolean isSelected) {Color bColor;if (isSelected) {bColor = UIManager.getColor("Tree.selectionBackground");} else {bColor = UIManager.getColor("Tree.textBackground");}super.setBackground(bColor);}void setFocus(boolean hasFocus) {if (hasFocus) {Color lineColor = UIManager.getColor("Tree.selectionBorderColor");setBorder(BorderFactory.createLineBorder(lineColor));} else {setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));}}}
}

这篇关于Swing之JTree篇:设置树选中节点背景色的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

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

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

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

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 提供了许多

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

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

uniapp设置微信小程序的交互反馈

链接:uni.showToast(OBJECT) | uni-app官网 (dcloud.net.cn) 设置操作成功的弹窗: title是我们弹窗提示的文字 showToast是我们在加载的时候进入就会弹出的提示。 2.设置失败的提示窗口和标签 icon:'error'是设置我们失败的logo 设置的文字上限是7个文字,如果需要设置的提示文字过长就需要设置icon并给

Tomcat性能参数设置

转自:http://blog.csdn.net/chinadeng/article/details/6591542 Tomcat性能参数设置 2010 - 12 - 27 Tomcat性能参数设置 博客分类: Java Linux Tomcat 网络应用 多线程 Socket 默认参数不适合生产环境使用,因此需要修改一些参数   1、修改启动时内存参数、并指定J

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

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

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

linux下非标准波特率的设置和使用

通常,在linux下面,设置串口使用终端IO的相关函数设置,如tcsetattr等函数,linux内部有一个对常用波特率列表的索引,根据设置的波特率用底层驱动来设置异步通信芯片的寄存器 对于非标准的任意波特率需要用ioctl(fd, TIOCGSERIAL, p)和ioctl(fd, TIOCSSERIAL, p)的配合,ioctl的最后一个参数是struct serial_struct *