/*
需求:列出指定目录的内容。
当目录不存在时给出出错信息。
建立一个Enter的键盘监听。
当输完文件路径后,可以选择按Enter直接转到
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class myWindowDemo
{
private Frame f;
private Button but;
private TextArea ta;
private TextField tf;
private Dialog d;
private Label lab;
private Button okBut;
myWindowDemo()
{
init();
}
public void init()
{
f = new Frame("my Window");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf = new TextField(50);
but = new Button("转到");
ta = new TextArea(25,80);
d = new Dialog(f,"提示信息",true);
d.setBounds(400,200,280,150);
d.setLayout(new FlowLayout());
lab = new Label();
okBut = new Button("确定");
d.add(lab);
d.add(okBut);
f.add(tf);
f.add(but);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
//窗体关闭
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
//对话框关闭
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
//“转到”按钮监听
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showDir();
}
});
//Enter的键盘监听
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
});
}
private void showDir()
{
String dirpath = tf.getText();
File dir = new File(dirpath);
if(dir.exists() && dir.isDirectory())//isDirectory()是检查一个对象是否是文件夹
{
ta.setText("");
String[] names = dir.list();
for(String name : names)
{
ta.appendText(name+"\r\n");
}
}
else
{
String info = "您输入的路径:"+dirpath+"是错误的,请重新输入。";
lab.setText(info);
d.setVisible(true);
}
}
public static void main(String[] args)
{
new myWindowDemo();
}
}