建立圖形化介面的基本流程:
1.先建立表單
2.對表單進行基本設定
比如:大小,顯示地區,是否可見等
3.建立組件
4.對組件進行基本設定
比如:大小,初始值等
5.將組件添加到相應表單中 設定監聽的方法
1.事件來源
2.事件
3.監聽器
4.處理方式
前三個都是已經被java封裝好了的,我們只需要拿來用即可,我們要做的事情就是,寫處理方式 需求:
1.如圖,設計一個介面如上圖的程式。
2.功能:
1.在文字框裡輸入檔案夾路徑,點轉到會在文本地區顯示該檔案夾裡的檔案和檔案夾名稱
2.當輸錯後,會有對話方塊提示輸入錯誤
3.直接按斷行符號也可以顯示檔案夾裡的內容
代碼實現:
import java.awt.*;import java.awt.event.*;import java.io.*;class FrameDemo {public static void main(String[] args) {new myWindow();}}class myWindow{private Frame f;private TextField tf;private Button but;private TextArea ta;private Dialog d;//此處一般是寫在出現錯誤的相關方法裡private Label lab;private Button okBut;myWindow(){init();}public void init(){f=new Frame("My Frame");//同時設定顯示地區和表單大小f.setBounds(400,500,600,500);//設定表單布局f.setLayout(new FlowLayout());//建立文字框tf=new TextField(20);//建立按鈕but=new Button("轉到");//建立文本地區ta=new TextArea(30,60);//添加組件到表單f.add(tf);f.add(but);f.add(ta);//建立對話方塊d=new Dialog(f,"提示資訊:",true);d.setBounds(450,650,300,100);d.setLayout(new FlowLayout());//建立lable標籤lab=new Label();//建立對話方塊按鈕okBut=new Button("確定");d.add(lab);d.add(okBut);//運行監聽事件myEvent();//設定表單可見f.setVisible(true);}public void myEvent(){//表單關閉f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});//轉到按鈕點擊事件but.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){showDir();}});okBut.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){showDir();}}});}public 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{lab.setText("您輸入的目錄:"+DirPath+"是錯誤的,請重新輸入。");d.setVisible(true);}}}