我的JTree有問題。 我的JTree顯示(音樂,文檔,圖片,視頻等)像Windows資源管理器。 例如,如果我點擊一個節點,並且此節點是包含5(或更多)圖像的文件夾 如何在5個單JLabels中顯示這5個圖像???如何通過點擊JTree節點來顯示內容
回答
有兩種方法可以解決這個問題。第一個(更容易)是將你的圖像直接添加到TreeModel中,以便它們由DefaultTreeCellRenderer或其擴展名呈現。第二,如果您不想將圖像添加到您的TreeModel,則會創建一個自定義TreeCellRenderer,它可以繪製一個Component中的所有圖像......但您可能會遇到這種方式的事件/佈局問題。
另外,瞭解JTree使用渲染器,並且您實際上不能將任何組件添加到JTree,您只能渲染數據項。
是,利用在容器標籤嵌套的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);
我已經向您展示如何存儲兩個圖像,你可以使用不同的佈局來存儲一個以上的圖像。
嗯謝謝你的快速回復。 我使用了GridLayout的allready,這不是問題,例如,如果你點擊左側窗口的瀏覽器中的節點,你會得到右側的內容。而在我的情況下,我想在JLabels中將這些內容顯示爲圖像。 – Blank 2014-10-27 14:38:36
沒有,你可以請詳細說明或你想要什麼,或者你可以把圖像,讓我們可以理解。當選民投票時,請留下評論。 – 2014-10-27 14:48:09
@Blank它意味着你想用你的縮略圖圖像來改變那個箭頭圖像以展開樹節點? – 2014-10-27 14:51:34
好吧,我用下面的代碼you'll讓您單擊的節點的路徑與此我知道了......
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);
得到路徑,現在我可以使用路徑來填充我的JLabels圖像。
感謝您的快速響應,這幫助我處理了TreeCellRenderer,但它解決了我的問題(但它幫助了很多),非常感謝。 – Blank 2014-10-27 15:31:16