天天看點

GUI學習筆記MyWindowDemo.java

import java.awt.*;

import java.awt.event.*;

import java.io.*;//還不會的知識

class MyWindowDemo //extends Frame

{

 private Frame f;

 private Button but;

 private TextField tf;

 private TextArea ta;

 private Dialog d;

 private Label lab;

 private Button okbut;

 MyWindowDemo()

 {

  init();

 }

 public void init()

 {

  f=new Frame("my window");

  f.setBounds(200,100,600,550);

  f.setLayout(new FlowLayout());

  tf=new TextField(60);

  f.add(tf);

  but=new Button("轉到");

  f.add(but);

  ta=new TextArea(15,70);

  f.add(ta);

  d=new Dialog(f,"提示資訊-self",true);

  d.setBounds(215,115,200,100);

  d.setLayout(new FlowLayout());

  lab=new Label();

  d.add(lab);

  okbut=new Button("确定");

  d.add(okbut);

  myEvent();

  f.setVisible(true);

 }

 public void myEvent()

 {

  f.addWindowListener(new WindowAdapter()

  {

   public void windowClosing(WindowEvent e)

   {

    System.exit(0);

   }

  }

  );

  okbut.addActionListener(new ActionListener()

  {

   public void actionPerformed(ActionEvent e)

   {

    d.setVisible(false);

   }

  }

  );

  d.addWindowListener(new WindowAdapter()

  {

   public void windowClosing(WindowEvent e)

   {

    d.setVisible(false);

   }

  }

  );

  but.addActionListener(new ActionListener()

  {

   public void actionPerformed(ActionEvent e)

   {

    showDir();

    //ta.setText("你錯誤了");

   }

  }

  );

  tf.addKeyListener(new KeyAdapter()

  {

   public void keyPressed(KeyEvent e)

   {

    if(e.getKeyCode()==KeyEvent.VK_ENTER)

    {

     showDir();

    }

   }

  }

  );

  okbut.addKeyListener(new KeyAdapter()

  {

   public void keyPressed(KeyEvent e)

   {

    if(e.getKeyCode()==KeyEvent.VK_ENTER)

     d.setVisible(false);

   }

  }

  );

 }

 public void showDir()

 {

  String dirPath=tf.getText();//還不會的知識

  File dir=new File(dirPath);

  if(dir.exists() && dir.isDirectory())

  {

   String[] names=dir.list();

   for(String name : names)

   {

    tf.setText("");

    ta.append(name+"\r\n");

   }

  }

  else

  {

   String info="你輸入資訊:"+dirPath+"是錯誤的。請重輸!";

   lab.setText(info);

   d.setVisible(true);

  }

 }

 public static void main(String[] args)

 {

  new MyWindowDemo();

 }

}