黑马程序员技术交流社区
标题:
图形化界面显示目录
[打印本页]
作者:
MUFCRyanCR7
时间:
2015-9-17 14:06
标题:
图形化界面显示目录
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class FrameDemo {
private Frame f;
private TextField tf ;
private TextArea ta;
private Button b1,b2;
private Dialog d;
private Label lab;
FrameDemo()
{
init();
}
private void init()
{
f = new Frame("显示指定目录");
tf = new TextField(35);
ta = new TextArea(25,40);
b1 = new Button("转到");
d = new Dialog(f,"错误提示",true);
b2 = new Button("确定");
lab = new Label("您输入的路径有误,请检查");
f.setBounds(200, 100, 500, 600);
f.setLayout(new FlowLayout());
f.add(tf);
f.add(b1);
f.add(ta);
d.setBounds(500,300,300,100);
d.setLayout(new FlowLayout());
d.add(lab);
d.add(b2);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
//通过按钮“转到”实现目录输出功能及对话框弹出功能
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
showDir();
}
});
//实现对话框的窗口关闭功能
d.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
//实现对话框上的按钮“确定”的功能
b2.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();
}
}
});
b2.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
d.setVisible(false);
}
}
});
}
private void showDir()
{
String dirPath = tf.getText();
File dir = new File(dirPath);
if(dir.exists()&&dir.isDirectory())
{
ta.setText("");
File[] file = dir.listFiles();
for(File f : file)
{
ta.append(f.getName()+"\r\n");
}
}
else
{
String info= "你输入的路径:"+dirPath+"有误,请重输";
lab.setText(info);
d.setVisible(true);
}
}
public static void main(String[] args) {
new FrameDemo();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2