/*
window demo 控制类
*/
package en.itcast.java.tools;
import java.awt.*;
import java.io.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyWindowDemo {
private Frame f;
private Button b;
private TextField tf;
private TextArea ta;
private Dialog d;
private Label l;
private Button okbut;
MyWindowDemo()
{
init();
}
public void init()
{
f=new Frame("my window");
f.setBounds(40,30,1000,600);
f.setVisible(true);
f.setLayout(new FlowLayout());
tf=new TextField(10);//设置最好可以接受多少个字符
b=new Button("转到");
ta=new TextArea(25,70);
d=new Dialog(f,"提示信息---self",true);
d.setBounds(400,200,240,150);
//d.setVisible(true);//发现多写了一句
d.setLayout(new FlowLayout());
l=new Label();
okbut=new Button("确定");
//把确定按钮和label 标签添加到对话框中
d.add(l);
d.add(okbut);
//把文本区,文本域和一个button按钮添加到框架中去
f.add(ta);
f.add(tf);
f.add(b);
myEvent();
}
private void myEvent()
{
//为对话框中的按钮添加鼠标监听事件,使一点击按钮就隐藏此窗体(对话框)
okbut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
d.setVisible(false);
}
});
//为对话框添加窗体监听机制,关闭时,隐藏对话框窗口
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
//为文本域添加键盘监听机制
//在tf中敲击回车键的时候,执行showDir函数
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
});
//为窗体里的按钮事件添加行为监听事件
//尚未输入内容的时候,单击回车的时候,也会执行一次showDir函数
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
showDir();
}
} );
//为窗体添加关闭事件
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
private void showDir()
{
String dirPath=tf.getText();
File dir=new File(dirPath);
//如果文件存在文件目录也存在那么
if(dir.exists()&&dir.isDirectory())
{
ta.setText("");//先保持文本域是空的
String[] names=dir.list();
for(String name :names)
{
ta.append(name+"\r\n");
//斜杠r是换行,斜杠t是制表符,斜杠n是
}
}
else
{
String info="你输入的信息:"+dirPath+"是错误的的。请重新输入";
//将字符串中的信息呈现在label标签中
//将对话框显现出来,对话框是Diarlog
l.setText(info);
d.setVisible(true);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyWindowDemo();
}
}
|