本章重點:
- 善用物件導向功能,透過class(類別)中的method(方法)傳遞,減少宣告時的繁複程式碼。(method(方法)的功能類似於C語言function(函數)的存在)
- Polymorphism多型:當子類別互相傳遞時會有衝突,此時可以將改成透過共通的父類別來傳遞
- implements Interface,實作界面除了直接在class實作之外,也能在event物件註冊時實作出來
請看以下說明:
import java.awt.*; import java.awt.event.*; public class c001 extends Frame{ /*Variable*/ Button bt01; boolean mode=false; /*Constructor*/ c001(){ Init.InitWin(this); bt01 = new Button("On"); Init.setButton(bt01, 80, 50, 100, 100); Init.addWinListen(this); this.add(bt01); bt01.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { if(mode==false){ bt01.setLabel("Off"); mode = true; }else{ bt01.setLabel("On"); mode=false; } } } ); } /*MAIN*/ public static void main(String[] args){c001 mm = new c001();} }
另外製作一個class Init類別來承裝多餘的程式碼,例如:Init.InitWin(this); 就是設定window的性質
看到 bt01.addActionListener 這行,這邊是要將按鈕bt01註冊ActionListener,此時可以接著實作界面裡的方法actionPerformed;寫法就是在bt01.addActionListener後的括號中 new ActionListener(),生成後便可實作方法actionPerformed
import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class Init { /*polymorphism*/ public static void InitWin(Frame v){ v.setSize(1000,800); v.setLocation(500,100); v.setLayout(null); v.setVisible(true); } public static void addWinListen(Frame v){ /*Interface*/ v.addWindowListener( new WindowListener(){ /*WindowListener Method*/ public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {v.dispose();} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} } ); } public static void setButton(Button b, int weigh, int height, int x, int y){ b.setSize(weigh,height); b.setLocation(x,y); } }
注意看「public static void InitWin(Frame v){ 」這行,括號內不是用 c001 v,而是用c001的父類別Frame,好處是以後增加其他Frame的子類別時,Init.InitWin還是可以使用,不必特別更改
文章標籤
全站熱搜