1. 程式人生 > >GUI之練習——列出指定目錄下的內容和對話方塊(Dialog)

GUI之練習——列出指定目錄下的內容和對話方塊(Dialog)

package myclass;

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

     but = new Button("轉到");

     ta = new TextArea(15,40);


     d = new Dialog(f,"提示資訊—self",true);
     d.setBounds(400,200,240,150);
     d.setLayout(new FlowLayout());
     lab = new Label();
     okBut = new Button("確定");
  
     d.add(lab);
     d.add(okBut);


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

     myEvent();
     f.setVisible(true);

}
private void myEvent()
{
    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();
            } 
      });
     okBut.addActionListener(new ActionListener()
     {
           public void actionPerformed(ActionEvent e)
           {
               d.setVisible(false);
           }
      });
    f.addWindowListener(new WindowAdapter()
    {
         public void windowClosing(WindowEvent e)
         {
               System.exit(0);
          }
    });
    but.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            showDir();
      
           /* else 
            {
               String info = "您輸入的資訊是錯誤的" +dirPath+"請從新輸入";
               lab.setText(info);
               d.setVisible(true);
            }*/
             
            //ta.setText(dirPath);
            //tf.setText("");
           // System.out.println(text);
        }
    });
}
 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)
           {
              ta.append(name+"\r\n");
            }
        }
       else 
            {
               String info = "您輸入的資訊是錯誤的" +dirPath+"請從新輸入";
               lab.setText(info);
               d.setVisible(true);
            }
        tf.setText("");
  }
 public static void main(String[] args)
 {
       new MyWindowDemo();
  }

}