JTree实现文件树

这篇文章介绍的内容其实跟TWaver的组件没有任何关系,但是个人觉得还是挺有意思的,所以发出来共享一下。这个文件树(如下图)完全基于swing的JTree组件实现,先看一下最后我们完成的效果:

运行截图:


功能介绍:

  • 树状呈现文件系统结构
  • 文件的图标应该使用系统图标
  • 鼠标滑过时改变当前节点的背景色(如图中"Windows"节点的砖红色背景)

先看一下类结构:

  • FileTreeTest 程序入口
  • FileTree 文件树,从JTree继承
  • FileNode 封装的文件节点,包括文件名,文件图标和实际的File类及其它标识
  • FileTreeRenderer 定制的节点渲染器,从DefaultTreeCellRenderer继承
  • FileTreeModel 定制的TreeModel,从DefaultTreeModel继承


考虑到系统文件会很多,在程序开始就初始化整个树是不现实的,所以我采取一种延迟加载的策略,只有当要展开某个节点的时候,才去初始化它的子节点,在FileTree的构造里加一个监听:

 

 

addTreeWillExpandListener(new TreeWillExpandListener() {
            @Override
            public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
                DefaultMutableTreeNode lastTreeNode =
(DefaultMutableTreeNode) event.getPath().getLastPathComponent();
                FileNode fileNode = (FileNode) lastTreeNode.getUserObject();
                if (!fileNode.isInit) {
                    File[] files;
                    if (fileNode.isDummyRoot) {
                        files = fileSystemView.getRoots();
                    } else {
                        files = fileSystemView.getFiles(
                                ((FileNode) lastTreeNode.getUserObject()).file,
                                false);
                    }
                    for (int i = 0; i < files.length; i++) {
                       //文件名和图标都是通过fileSystemView得到
                        FileNode childFileNode = new FileNode(
                                fileSystemView.getSystemDisplayName(files[i]),
                                fileSystemView.getSystemIcon(files[i]), files[i],
                                false);
                        DefaultMutableTreeNode childTreeNode = new DefaultMutableTreeNode(childFileNode);
                        lastTreeNode.add(childTreeNode);
                    }
                    //通知模型节点发生变化
                    DefaultTreeModel treeModel1 = (DefaultTreeModel) getModel();
                    treeModel1.nodeStructureChanged(lastTreeNode);
                }
                //更改标识,避免重复加载
                fileNode.isInit = true;
            }
            @Override
            public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {

            }
        });
 

当然这种方式需要TableModel的配合,我重载了DefaultTreeModel,在构造里初始化根节点,然后重载isLeaf方法,具体代码可以下载附件查看。

接下来思考一下鼠标滑过改变背景色怎么实现。
写这段代码的时候,我想起来了我刚学Renderer的时候的一个错误的认识:误以为每个节点都有一个Renderer并且妄图在Renderer上加监听!在此强调一下:Renderer只是一个渲染器,要显示节点的时候,JTree就调用它渲染并画到屏幕上,但是无论有多少节点,一个JTree只有一个Renderer!
Renderer上加监听行不通,我们就转换一下思路,在JTree上加鼠标move监听,然后repaint鼠标所在的节点。

 

 

addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
//获得鼠标所在的TreePath
                TreePath path=getPathForLocation(e.getX(), e.getY());

//计算repaint的区域并repaint JTree
                if(path!=null){
                    if(mouseInPath!=null){
                        Rectangle oldRect=getPathBounds(mouseInPath);
                        mouseInPath=path;
                        repaint(getPathBounds(path).union(oldRect));
                    }else{
                        mouseInPath=path;
                        Rectangle bounds=getPathBounds(mouseInPath);
                        repaint(bounds);
                    }
                }else if(mouseInPath!=null){
                    Rectangle oldRect=getPathBounds(mouseInPath);
                    mouseInPath=null;
                    repaint(oldRect);
                }
            }
        });
 

需要在JTree中保存鼠标滑过的TreePath(mouseInPath),这样在Renderer中才可以改变mouseInPath的背景色

 

 

FileTree fileTree=(FileTree)tree;
        JLabel label= (JLabel) super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);

        DefaultMutableTreeNode node=(DefaultMutableTreeNode)value;
        FileNode fileNode=(FileNode)node.getUserObject();
        label.setText(fileNode.name);
        label.setIcon(fileNode.icon);

        label.setOpaque(false);
//如果当前渲染的节点就是鼠标滑过的节点,改变背景色
        if(fileTree.mouseInPath!=null&&
                fileTree.mouseInPath.getLastPathComponent().equals(value)){
            label.setOpaque(true);
            label.setBackground(new Color(255,0,0,90));
        }
        return label;


至此这个文件树就写完了!全部代码在附件,有兴趣的同学可以下载看看,也希望看过的同学有好的想法来交流一下。

附件:见原文最下方

Swing JTree的使用及常用方法、常用功能实现 JTree的使用及常用方法、实现本地文件树、实现下拉列表树、节点的拖拽功能实现等 阅读详情

相关推荐

JTree设置不同图标

JTree设置QQ好友树形列表中不同好友的图像,采用swing组件

java jtree 图标_请问怎样设置JTree对象的图标

请问怎样设置JTree对象的图标|有不同的办法:1.利用UIManager类,IconopenIcon=newImageIcon("open.gif");IconcloseIcon=newImageIcon("close.gif");IconleafIcon=newImageIcon("leaf.gif");UIManager.put("Tree.closeIcon",clo...

weixin_42514930的博客 626

l0phtcrack 7(爆破管理员密码)使用教程

l0phtcrack7简称lc7,是爆破计算机管理员密码的软件,早期是网络安全管理员用来检测系统用户是否使用了不安全的密码,后被黑客用于用户口令破解 功能:该工具支持远程破解,理论上能破解所有密码,但对复杂度比较高的密码,破解时间很长 使用前提:1.登录了需要破解的计算机 2.知道需要破解的计算机的一个管理员的账户,密码 ** 也许你会疑惑,我都知道了一个管理员账户密码了,还要另外的管理员密码...

Xiongcanne的博客 2万+

java jtree 图标,Java:JTree带有正/负图标,用于扩展和折叠?

How do I make my Jtree look like something below, with plus and minus icons that allows expansion and collapse?Currently, the default JTree only expands and collapses when you double click. I want to ...

weixin_39653448的博客 131

Ubuntu 20.04下IgH EtherCAT主站部署实战

本文详细介绍了在Ubuntu 20.04系统上部署IgH EtherCAT主站的完整流程,包括环境准备、源码编译、内核模块配置、网络接口设置及实时性优化等关键步骤。通过实战案例和常见问题排查,帮助开发者快速掌握EtherCAT主站部署技巧,提升工业自动化系统的稳定性和实时性。

weixin_30596343的博客 1070

elasticsearch-6.5.4集群部署(图文详细)及常见错误

目录 服务器规划 部署包下载 服务器初始化(所有节点都要操作) 内核参数修改 /etc/security/limits.conf修改 /etc/sysctl.conf文件修改 禁用selinux 关闭防火墙 创建es用户 安装jdk es部署 单节点(节点1)部署 部署包上传解压 配置文件修改 修改文件属组 部署包分发 单节点(节点2)部署 配置文件修改 修改文件属组 单节点(节点3)部署 配置文件修改 修改文件属组 启动ES集群 验证 单节点验证 查看集

夜灬狼丶 1975

修改JTree的图标

/** * 改变树的图标,图标的图片放到image文件夹当中 * @param tree */ public static void setChangeTreeUI(JTree tree){ tree.setRootVisible(false);//是否显示根节点 tree.setShowsRootHandles(tr

聆听梦飞扬的博客 4842

【七.三维视觉与视频分析】【1.点云处理:PointNet++/PointTransformer】

各位老铁,今天咱们要聊的可不是普通的二维图像处理,而是三维视觉领域最硬核的技术——点云处理。从最早的PointNet到如今的PointTransformer,这场技术进化堪比三维版的"像素革命"。今天咱们就深入解剖两大里程碑:PointNet++和PointTransformer,保证让你看完全文就能在点云领域横着走!想象一下,你抓了把沙子撒在空中,每粒沙子的位置都是三维坐标——这就是点云的典型形态。最后送大家一句话:点云处理就像在三维宇宙中寻找星辰的轨迹,既要望远镜的宏观视野,也要显微镜的细致入微。

商务合作|问题讨论|交流学习 请联系作者微信,加微信请务必注明来意,博客主页有联系方式 473

JTree实现文件树——使用系统图标

这篇文章介绍的内容其实跟TWaver的组件没有任何关系,但是个人觉得还是挺有意思的,所以发出来共享一下。这个文件树(如下图)完全基于swing的JTree组件实现,先看一下最后我们完成的效果: 运行截图:

我的专栏 4801

昇腾,Ascend,NPU,mindie,镜像,部署vllm:第5篇,昇腾环境下部署蒸馏版deepseek-r1,并在dify中注册模型供应商

这两天没少折腾deepseek-r1。之前在A100上用ollama部署了一份DeepSeek-R1-Distill-Qwen-32B,感觉真的特别慢。现在,再用昇腾部署一遍,看看速度能不能更快。p.s. 类似的内容其实已经写了很多遍了。但感觉之前写得都太碎,不够顺畅。接着新模型写篇长文,把能包括的都包括进来。这样大家也不需要到处翻来翻去。

xiezhipu的博客 2450

工业相机的检测原理课件(建议收藏)

本课件为各位工程师详细介绍了工业相机的视觉检测原理 ,旨在为工程师调试工业相机的视觉检测原理时提供理论性指导。

Bamboo265925的博客 498

java文件树_JAVA实现文件树

public class ExplorerTree extends JPanel {private JTree tree;private TreePath treePath;public ExplorerTree() {this.setLayout(new BorderLayout());DefaultMutableTreeNode root = new DefaultMutableTreeNod...

weixin_30474629的博客 407

Unitree G1仿人机器人协同搬箱:从仿真搭建到多机协同部署完整指南

Unitree G1仿人机器人协同搬箱技术方案摘要 本文提供了一套完整的Unitree G1人形机器人协同搬箱解决方案,涵盖从仿真环境搭建到多机协同部署的全流程。核心内容包括: 双仿真环境配置:同时搭建Gazebo+ROS Noetic基础仿真环境与Isaac Gym+Mujoco高性能RL训练环境,支持Sim2Sim迁移验证 训练框架搭建:详细配置unitree_rl_gym框架,提供PPO算法定制化训练流程和参数优化方案 数据集应用:整合宇树开源真机数据集(UnifoLM-WBT-Dataset)~~~

huanghm88的专栏 471

JAVA实现文件树

你想你的Swing程序拥有像资源管理器一样的树吗?还要Lazy loading的吗? 那就看看我下面实现的文件树代码 public class ExplorerTree extends JPanel { private JTree tree; private TreePath treePath; public ExplorerTree() { ...

weixin_33728708的博客 98

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Java 实现"我的电脑"资源管理器(JTree,JTable)

几天的努力,辛辛苦苦的总算把这个资源管理器给做了出来,总体上讲目前虽然实现了管理器功能,但是代码显得很混乱,并未实现界面与数据的分离,界面设计,监听Listener,数据处理的所有代码只是写在一个类中.     现代编程思想把程序分成界面展示层、业务罗基层和数据访问层。界面展示层负责和用户交互,界面层的输入或者查询请求首先告诉业务逻辑层,业务逻辑模块根据分析业务、查找缓存等等操作决定是否访问

杨名天吓 3756

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java的包资源管理器怎么弄出来_怎样对java中包资源管理器排序

展开全部给你看看32313133353236313431303231363533e78988e69d8331333337386562我的实现方法,希望对你有帮助classMyTreeextendsJTreeimplementsTreeExpansionListener,TreeSelectionListener{FileFilterfilterDirectory=newFile...

weixin_35291771的博客 535

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

【Java】 实现一个简单文件浏览器(1)

学习Java的Swing的时候写的一个超简单文件浏览器 效果如图: 项目结构: 这里面主要用了两个控件,JTree和JTable 下面先说下左侧的文件树如何实现: 首先是FileTree类,继承于JTree类,这里实现了树节点展开,和鼠标移动事件响应 package FileTree; import java.awt.Rectangle; import ja...

weixin_34378767的博客 656

java项目资源管理器_一个用Java实现的Windows资源管理器

1.[代码]FileTree.java// FileTree.java/************************************************************ Author: Jason* email: tl21cen@hotmail.com* 优快云 blog: http://blog.youkuaiyun.com/UnAgain/*************...

weixin_42112894的博客 252

把目录用树画出来

 package csdn;import javax.swing.*; import javax.swing.tree.*; import java.awt.*; import java.io.*;public class TreeDir extends JFrame { private static final long serialVersionUID = 1L;  public Tree

lz12366007的专栏 847

java文件浏览器_【Java】 实现一个简单文件浏览器(1)

学习Java的Swing的时候写的一个超简单文件浏览器效果如图:项目结构:这里面主要用了两个控件,JTree和JTable下面先说下左侧的文件树如何实现:首先是FileTree类,继承于JTree类,这里实现了树节点展开,和鼠标移动事件响应package FileTree;import java.awt.Rectangle;import java.awt.event.MouseAdapter;im...

weixin_35962107的博客 448
上一篇: TWaver 3D for Flex 3.0发布
下一篇: TWaver HTML5 继承结构和成员说明
subnetwork
博客等级 码龄17年 17粉丝 84原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值