一个用swt做的简单的文件浏览器,
package hello;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
public class TreeShellExample {
Display d;
Shell s;
public TreeShellExample() {
d = new Display();
s = new Shell(d);
s.setSize(250, 200);
s.setImage(new Image(d, "c:/cart.png"));
s.setText("A Tree Shell Example");
s.setLayout(new FillLayout());
final Tree t = new Tree(s, SWT.SINGLE | SWT.BORDER);
File[] roots = File.listRoots();
for(int i = 0; i < roots.length; i++) {
TreeItem root = new TreeItem(t, SWT.NONE, i);
String name = roots[i].getAbsolutePath();
if(name.endsWith("\\")) {
name = name.substring(0, name.length() - 1);
}
root.setText(name);
root.setImage(new Image(d, "c:/image/folder.gif"));
TreeItem child = new TreeItem(root, SWT.NONE, 0);
}
t.addTreeListener(new TreeListener() {
public void treeExpanded(TreeEvent e) {
TreeItem ti = (TreeItem)e.item;
ti.setImage(new Image(d, "c:\\image\\open.gif"));
TreeItem item = ti;
List<String> list = new LinkedList<String>();
while(item != null) {
list.add(0, item.getText());
item = item.getParentItem();
}
String path = privateConvertToString(list);
File[] children = new File(path).listFiles();
ti.removeAll();
if(children != null) {
for(int i = 0; i < children.length; i++) {
TreeItem child = new TreeItem(ti, SWT.NONE, i);
child.setText(children[i].getName());
if(children[i].isDirectory()) {
child.setImage(new Image(d, "c:/image/folder.gif"));
new TreeItem(child, SWT.NONE, 0);
} else if(children[i].isFile()) {
child.setImage(new Image(d, "c:/image/file.gif"));
}
}
}
}
public void treeCollapsed(TreeEvent e) {
TreeItem ti = (TreeItem)e.item;
ti.setImage(new Image(d, "c:\\image\\folder.gif"));
}
});
s.open( );
while(!s.isDisposed( )){
if(!d.readAndDispatch( ))
d.sleep( );
}
d.dispose( );
}
private String privateConvertToString(List<String> list) {
StringBuffer buffer = new StringBuffer();
if(list.size() == 1) {
return buffer.append(list.get(0) + "/").toString();
} else {
for(int i = 0; i < list.size(); i++) {
buffer.append(list.get(i));
if(i != list.size() - 1) {
buffer.append("/");
}
}
return buffer.toString();
}
}
public static void main(String[] args) {
new TreeShellExample();
}
}