import java.awt.*;
import java.awt.event.*;
import java.io.*;
class GUIdemo{
private Frame f;
private Button b;
private TextField t;
private TextArea ta;
public GUIdemo(){
init();
myevent();
}
public void init(){
f=new Frame();
f.setBounds(300,100,600,500);
t=new TextField(30);
ta=new TextArea(20,50);
t.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
ta.setText("");
String dir=t.getText();
File file=new File(dir);
if(file.exists() && file.isDirectory()){
int level=0;
show(file,ta,level);
}
else
ta.setText("文件路径非法或不存在");
}
}
});
b=new Button("显示");
b.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
ta.setText("");
String dir=t.getText();
File file=new File(dir);
if(file.exists() && file.isDirectory()){
int level=0;
show(file,ta,level);
}
else
ta.setText("文件路径非法或不存在");
}
});
f.add(t);
f.add(b);
f.add(ta);
f.setLayout(new FlowLayout());
f.setVisible(true);
}
public void myevent(){
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
private void show(File file,TextArea ta,int level){
level++;
if(file.isDirectory()){
for(int i=0;i<level-1;i++)
ta.append("—");
ta.append(file.getName()+"\r\n");
File[] files=file.listFiles();
for(File f:files)
show(f,ta,level);
}else{
for(int i=0;i<level-1;i++)
ta.append("—");
ta.append(file.getName()+"\r\n");
}
}
public static void main(String[] args){
new GUIdemo();
}
} |
|