GUI用法

来源:互联网 发布:北京软件行业协会官网 编辑:程序博客网 时间:2024/06/08 02:48
/*列出指定目录的所有内容*/package gui4;import java.awt.*;import java.awt.event.*;import java.io.*;class  GUIDemo4{private Frame f;private TextField tf;private TextArea ta;private Button btn;private Dialog d;private Label lab;private Button okBtn;GUIDemo4(){init();}//初始化组件public void init(){f=new Frame("窗口");tf=new TextField(40);ta=new TextArea(50,80);btn=new Button("转到");f.setBounds(300,100,600,500);f.setLayout(new FlowLayout());f.add(tf);f.add(btn);f.add(ta);d=new Dialog(f,"提示",true);d.setBounds(300,200,240,150);d.setLayout(new FlowLayout());lab=new Label();okBtn=new Button("确定");d.add(lab);d.add(okBtn);myEvent();f.setVisible(true);}//添加事件public void myEvent(){//窗口事件f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});//动作事件btn.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){get();}});        //对话框窗口监听事件d.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){d.setVisible(false);}});       //对话框按钮监听事件okBtn.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){get();}}});}//取得目录的内容private  void get(){                String path=tf.getText();File dir=new File(path);                if(dir.exists() && dir.isDirectory()){ta.setText("");String[] str=dir.list();for (String name: str){ta.append(name+"\r\n");}}else {String info="输入的"+path+"有误,请重新输入!";//System.out.println(info);lab.setText(info);d.setVisible(true);}}public static void main(String[] args) {new GUIDemo4();}}

0 0
原创粉丝点击