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


//仅作为学习笔记

源码

// 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();
	}
	

}







  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值