【java編程】GUI之綜合練習(一)

來源:互聯網
上載者:User
建立圖形化介面的基本流程:

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.