[英]How to display content by clicking on a JTree node
我的JTree有问题。 我的JTree像Windows资源管理器一样显示(音乐,文档,图片,视频等)。 例如,如果我单击一个节点,并且该节点是一个包含5张(或更多)图像的文件夹,我如何在5个单个JLabel中显示这5张图像?
有两种方法可以解决此问题。 首先(更轻松)是将您的Images直接添加到TreeModel中,以便它们由DefaultTreeCellRenderer或其扩展名呈现。 第二个,如果您不想将图像添加到TreeModel中,则将创建一个自定义TreeCellRenderer,它将所有图像绘制在一个Component中...但是您可能会因事件/布局而遇到问题。
另外,请了解JTree使用Renderer,并且您实际上不能向JTree添加任何组件,而只能渲染数据项。
好的,我用以下代码得到它,您将获得您单击的节点的路径...
MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { TreePath selPath=MyTree.getPathForLocation(e.getX(), e.getY()); // <--- this was the part I searched for!
System.out.println(selPath);
if(selPath != null) {
if(e.getClickCount() == 1) {
mySingleClick(selPath);
}
else if(e.getClickCount() == 2) {
//myDoubleClick(selPath);
}
}
}
private void mySingleClick(TreePath selPath) {
// do whatever
}
};
MyTree.addMouseListener(ml);
有了这个,我得到了路径,现在我可以使用该路径用图像填充我的JLabel了。
是的,在容器标签中将嵌套的JLabel与BoxLayout一起使用:
JLabel mycontainer = new JLabel();
container.setLayout(new BoxLayout(mycontainer, BoxLayout.X_AXIS));
JLabel icon1Label = new JLabel();
JLabel icon2Label = new JLabel();
icon1Label.setIcon(icon1);
icon2Label.setIcon(icon2);
mycontainer.add(icon1Label);
mycontainer.add(icon2Label);
我已经向您展示了如何存储两个图像,您可以使用不同的布局来存储多个图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.