[英]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.