您的位置:首页 > 产品设计 > UI/UE

JAVA GUI(列出指定目录内容)

2013-04-07 22:24 543 查看
//仅作为学习笔记

源码

// GUI 练习  列出指定目录

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(63);

but =  new Button("转到");

ta = new TextArea(25,70);//设置行数和列数

d = new Dialog(f,"提示信息",true);
d.setBounds(400,200,240,150);
d.setLayout(new FlowLayout());
lab = new Label();
okBut = new Button("确定");

f.add(tf);
f.add(but);
f.add(ta);

d.add(lab);
d.add(okBut);

myEvent();

f.setVisible(true);
}

private void myEvent()
{
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});

d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);//设为不可见
}
});

tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
showDir();
}
});

but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
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)
{
//setText该方法只会输出最后一个目录 因为后面的覆盖前面的
//ta.setText(name + "\r\n");
ta.append(name + "\r\n");//将给定文本追加到文本区的当前文本
}
}
else
{
String info = "系统无法找到" +tf.getText() + "请从新输入!";
lab.setText(info);
d.setVisible(true);
}
tf.setText("");
}

public static void main(String []args)
{
new MyWindowDemo();
}

}






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: