我是新来JTrees并有一个查询:添加到JTree的JFileChooser的
如果我们能在JFileChooser
添加文件和可用目录的tree
在我们的系统。基本上我想有一个自定义JFileChooser,其中的文件和目录可以以树的形式显示。
感谢提前:)
我创建了正在我的系统目前的文件,但如何显示在树JFileChooser的一棵树。这里是JTree的代码
public class FileTree extends JPanel {
/** Construct a FileTree */
public FileTree(File dir) {
setLayout(new BorderLayout());
// Make a tree list with all the nodes, and make it a JTree
JTree tree = new JTree(addNodes(null, dir));
// Lastly, put the JTree into a JScrollPane.
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
add(BorderLayout.CENTER, scrollpane);
}
/** Add nodes from under "dir" into curTop. Highly recursive. */
DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir)
{
String curPath = dir.getPath();
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
if (curTop != null) { // should only be null at root
curTop.add(curDir);
}
Vector ol = new Vector();
String[] tmp = dir.list();
for (int i = 0; i < tmp.length; i++)
ol.addElement(tmp[i]);
Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
File f;
Vector files = new Vector();
// Make two passes, one for Dirs and one for Files. This is #1.
for (int i = 0; i < ol.size(); i++) {
String thisObject = (String) ol.elementAt(i);
String newPath;
if (curPath.equals("."))
newPath = thisObject;
else
newPath = curPath + File.separator + thisObject;
if ((f = new File(newPath)).isDirectory())
addNodes(curDir, f);
else
files.addElement(thisObject);
}
// Pass two: for files.
for (int fnum = 0; fnum < files.size(); fnum++)
curDir.add(new DefaultMutableTreeNode(files.elementAt(fnum)));
return curDir;
}
public Dimension getMinimumSize() {
return new Dimension(200, 400);
}
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
/** Main: make a Frame, add a FileTree */
public static void main(String[] av) {
JFrame frame = new JFrame("FileTree");
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
Container cp = frame.getContentPane();
if (av.length == 0) {
cp.add(new FileTree(new File(".")));
} else {
cp.setLayout(new BoxLayout(cp, BoxLayout.X_AXIS));
for (int i = 0; i < av.length; i++)
cp.add(new FileTree(new File(av[i])));
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
如果您的问题仅是答案是肯定的。如果你想知道如何,那么你的问题太广泛,无法回答。改为询问具体问题。 – talex
我知道这是广泛的,这就是为什么我无法理解从哪里开始,如果我需要做这样一个项目。 @talex。谢谢:) –
@bhavna garg你可以在'FileChooser'上使用'setAccesory(FileTree)'这种方法在'FileChooser'的右边添加'FileTree'。 –