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#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代

Pyserial设置缓冲区大小失败的问题解决

《Pyserial设置缓冲区大小失败的问题解决》本文主要介绍了Pyserial设置缓冲区大小失败的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录问题描述原因分析解决方案问题描述使用set_buffer_size()设置缓冲区大小后,buf

Feign Client超时时间设置不生效的解决方法

《FeignClient超时时间设置不生效的解决方法》这篇文章主要为大家详细介绍了FeignClient超时时间设置不生效的原因与解决方法,具有一定的的参考价值,希望对大家有一定的帮助... 在使用Feign Client时,可以通过两种方式来设置超时时间:1.针对整个Feign Client设置超时时间

PyCharm如何设置新建文件默认为LF换行符

《PyCharm如何设置新建文件默认为LF换行符》:本文主要介绍PyCharm如何设置新建文件默认为LF换行符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录PyCharm设置新建文件默认为LF换行符设置换行符修改换行符总结PyCharm设置新建文件默认为LF

Linux上设置Ollama服务配置(常用环境变量)

《Linux上设置Ollama服务配置(常用环境变量)》本文主要介绍了Linux上设置Ollama服务配置(常用环境变量),Ollama提供了多种环境变量供配置,如调试模式、模型目录等,下面就来介绍一... 目录在 linux 上设置环境变量配置 OllamPOgxSRJfa手动安装安装特定版本查看日志在

Ubuntu中Nginx虚拟主机设置的项目实践

《Ubuntu中Nginx虚拟主机设置的项目实践》通过配置虚拟主机,可以在同一台服务器上运行多个独立的网站,本文主要介绍了Ubuntu中Nginx虚拟主机设置的项目实践,具有一定的参考价值,感兴趣的可... 目录简介安装 Nginx创建虚拟主机1. 创建网站目录2. 创建默认索引文件3. 配置 Nginx4

如何关闭 Mac 触发角功能或设置修饰键? mac电脑防止误触设置技巧

《如何关闭Mac触发角功能或设置修饰键?mac电脑防止误触设置技巧》从Windows换到iOS大半年来,触发角是我觉得值得吹爆的MacBook效率神器,成为一大说服理由,下面我们就来看看mac电... MAC 的「触发角」功能虽然提高了效率,但过于灵敏也让不少用户感到头疼。特别是在关键时刻,一不小心就可能触

Nginx配置系统服务&设置环境变量方式

《Nginx配置系统服务&设置环境变量方式》本文介绍了如何将Nginx配置为系统服务并设置环境变量,以便更方便地对Nginx进行操作,通过配置系统服务,可以使用系统命令来启动、停止或重新加载Nginx... 目录1.Nginx操作问题2.配置系统服android务3.设置环境变量总结1.Nginx操作问题

grom设置全局日志实现执行并打印sql语句

《grom设置全局日志实现执行并打印sql语句》本文主要介绍了grom设置全局日志实现执行并打印sql语句,包括设置日志级别、实现自定义Logger接口以及如何使用GORM的默认logger,通过这些... 目录gorm中的自定义日志gorm中日志的其他操作日志级别Debug自定义 Loggergorm中的

前端 CSS 动态设置样式::class、:style 等技巧(推荐)

《前端CSS动态设置样式::class、:style等技巧(推荐)》:本文主要介绍了Vue.js中动态绑定类名和内联样式的两种方法:对象语法和数组语法,通过对象语法,可以根据条件动态切换类名或样式;通过数组语法,可以同时绑定多个类名或样式,此外,还可以结合计算属性来生成复杂的类名或样式对象,详细内容请阅读本文,希望能对你有所帮助...