unpublished:eventhandling
目錄表
國立屏東大學 資訊工程系 物件導向程式設計
附B. AWT 範例程式碼
- Version 1
- Version 2
- Version 3
- Version 4 (a closable windows application)
0.1 BlackJack專案與Main.java
以下範例係使用NetBeans 8.1建立一個名為BlackJack的專案,其中包含有以下的Main.java程式:
package blackjack; public class Main { public static void main(String[] args) { // TODO code application logic here new BlackJackGame(); } }
0.2 Version 1 WindowListener的實作
以下為在BlackJack的專案中的BlackJackGame.java程式:
package blackjack; import java.awt.*; import java.awt.event.*; public class BlackJackGame { BlackJackGame() { Frame mainWin = new Frame(); mainWin.setVisible(true); mainWin.setSize(500, 500); mainWin.setLocation(300, 200); MyWindowListener listener = new MyWindowListener(); mainWin.addWindowListener(listener); } }
以及其實作至WindowListener的MyWindowListener.java
package blackjack; import java.awt.event.*; public class MyWindowListener implements WindowListener { public void windowOpened(WindowEvent e){} public void windowClosing(WindowEvent e) { System.exit(0); } 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){} }
0.3 Version 2 使用WindowAdapter
本節改以WindowAdapter來進行相關的程式設計,以下為程式碼列表:
package blackjack; import java.awt.*; import java.awt.event.*; public class BlackJackGame { BlackJackGame() { Frame mainWin = new Frame(); mainWin.setVisible(true); mainWin.setSize(500, 500); mainWin.setLocation(300, 200); MyWindowAdapter listener = new MyWindowAdapter(); mainWin.addWindowListener(listener); }
package blackjack; import java.awt.event.*; public class MyWindowAdapter extends WindowAdapter{ public void windowClosing(WindowEvent e) { System.exit(0); } }
0.4 Version 3 在BlackJackGame.java中定義WindowAdapter的子類別
package blackjack; import java.awt.*; import java.awt.event.*; public class BlackJackGame { BlackJackGame() { Frame mainWin = new Frame(); mainWin.setVisible(true); mainWin.setSize(500, 500); mainWin.setLocation(300, 200); MyNewWindowAdapter listener = new MyNewWindowAdapter(); mainWin.addWindowListener(listener); } } class MyNewWindowAdapter extends WindowAdapter{ public void windowClosing(WindowEvent e) { System.exit(0); } }
0.5 Version 4 在BlackJackGame.java中使用匿名與內嵌式類別
package blackjack; import java.awt.*; import java.awt.event.*; public class BlackJackGame { BlackJackGame() { Frame mainWin = new Frame(); mainWin.setVisible(true); mainWin.setSize(500, 500); mainWin.setLocation(300, 200); mainWin.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
unpublished/eventhandling.txt · 上一次變更: 2019/07/02 15:01 由 127.0.0.1