0
我試圖添加一個瀏覽文件到我的程序的能力。我想使用這裏的代碼:1(吉爾伯特的回答),但這對於讓JTree處於特定位置和大小非常重要。不幸的是,當我這樣做時,JTree在點擊它時不會「迴應」。不使用JTree沒有LayoutManager
下面的代碼:
public class Frame extends JFrame implements Runnable {
private DefaultMutableTreeNode root;
private DefaultTreeModel treeModel;
private JTree tree;
public File fileRoot;
public Frame(){
super("FileBrowser");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(480, 320);
setLocation(50,50);
getContentPane().setLayout(null);
fileRoot = new File("C:/");
root = new DefaultMutableTreeNode(new FileNode(fileRoot));
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setBounds(10, 39, 155, 177);
getContentPane().add(tree);
tree.setShowsRootHandles(true);
}
@Override
public void run() {
CreateChildNodes ccn = new CreateChildNodes(fileRoot, root);
new Thread(ccn).start();
}
}
主要類:
public class main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Frame());
}
}
當我評論
getContentPane().setLayout(null);
,讓JTree的補全幀,它的作品,因爲它應該
謝謝,它的工作原理!我知道一般來說,使用佈局管理器要好得多,但在我的情況下,我想在特定的屏幕上顯示我的程序,並且佈局不是關鍵特性,所以我選擇了更簡單的方法。 – Ch0mik18
爲了擴大這個答案中的內容,**最值得關注的事情是:Java GUI必須在不同的語言環境中使用不同的PLAF來處理不同的操作系統,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –
@ Ch0mik18在這種情況下,如果你接受我的答案是正確的,那將會很好。 –