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

相关文章

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

Qt 设置软件版本信息的实现

《Qt设置软件版本信息的实现》本文介绍了Qt项目中设置版本信息的三种常用方法,包括.pro文件和version.rc配置、CMakeLists.txt与version.h.in结合,具有一定的参考... 目录在运行程序期间设置版本信息可以参考VS在 QT 中设置软件版本信息的几种方法方法一:通过 .pro

PostgreSQL 默认隔离级别的设置

《PostgreSQL默认隔离级别的设置》PostgreSQL的默认事务隔离级别是读已提交,这是其事务处理系统的基础行为模式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录一 默认隔离级别概述1.1 默认设置1.2 各版本一致性二 读已提交的特性2.1 行为特征2.2

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

mtu设置多少网速最快? 路由器MTU设置最佳网速的技巧

《mtu设置多少网速最快?路由器MTU设置最佳网速的技巧》mtu设置多少网速最快?想要通过设置路由器mtu获得最佳网速,该怎么设置呢?下面我们就来看看路由器MTU设置最佳网速的技巧... 答:1500 MTU值指的是在网络传输中数据包的最大值,合理的设置MTU 值可以让网络更快!mtu设置可以优化不同的网

MySQL 设置AUTO_INCREMENT 无效的问题解决

《MySQL设置AUTO_INCREMENT无效的问题解决》本文主要介绍了MySQL设置AUTO_INCREMENT无效的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录快速设置mysql的auto_increment参数一、修改 AUTO_INCREMENT 的值。

详解Linux中常见环境变量的特点与设置

《详解Linux中常见环境变量的特点与设置》环境变量是操作系统和用户设置的一些动态键值对,为运行的程序提供配置信息,理解环境变量对于系统管理、软件开发都很重要,下面小编就为大家详细介绍一下吧... 目录前言一、环境变量的概念二、常见的环境变量三、环境变量特点及其相关指令3.1 环境变量的全局性3.2、环境变

安装centos8设置基础软件仓库时出错的解决方案

《安装centos8设置基础软件仓库时出错的解决方案》:本文主要介绍安装centos8设置基础软件仓库时出错的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录安装Centos8设置基础软件仓库时出错版本 8版本 8.2.200android4版本 javas

Ubuntu设置程序开机自启动的操作步骤

《Ubuntu设置程序开机自启动的操作步骤》在部署程序到边缘端时,我们总希望可以通电即启动我们写好的程序,本篇博客用以记录如何在ubuntu开机执行某条命令或者某个可执行程序,需要的朋友可以参考下... 目录1、概述2、图形界面设置3、设置为Systemd服务1、概述测试环境:Ubuntu22.04 带图

VSCode设置python SDK路径的实现步骤

《VSCode设置pythonSDK路径的实现步骤》本文主要介绍了VSCode设置pythonSDK路径的实现步骤,包括命令面板切换、settings.json配置、环境变量及虚拟环境处理,具有一定... 目录一、通过命令面板快速切换(推荐方法)二、通过 settings.json 配置(项目级/全局)三、