练习 窗体和对话框Dialog

import java.awt.*;
import java.awt.event.*;
import java.io.*;


class  MyWindowDemo
{
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;


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("转到");
//TextArea 对象是显示文本的多行区域。可以将它设置为允许编辑或只读。
ta = new TextArea(25,65);//行,列


d = new Dialog(f,"提示信息-self",true);
//又设置提示框
d.setBounds(400,200,200,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()
{
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});


//添加键盘监听
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
});


d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});


but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showDir();


//ta.setText(text);
//System.out.println(text);


//tf.setText("");
}
});


f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

}


//封装成一个功能函数,方便调用
private void showDir()
{
//操作谁就去谁那找方法
String dirPath = tf.getText();
//通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。
File dir = new File(dirPath);


if (dir.exists() && dir.isDirectory())
{
//清空文本区域
ta.setText("");
String[] names = dir.list();
for(String name : names)
{
//ta.setText(name+"\r\n");
ta.append(name+"\r\n");
}
}
else
{
String info = "您输入的信息:"+dirPath+"错的,重输";
lab.setText(info);
d.setVisible(true);
}
}





public static void main(String[] args) 
{
new MyWindowDemo();
}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值