國立屏東大學 資訊工程系 物件導向程式設計
以下範例係使用NetBeans 8.1建立一個名為BlackJack的專案,其中包含有以下的Main.java程式:
package blackjack; public class Main { public static void main(String[] args) { // TODO code application logic here new BlackJackGame(); } }
以下為在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){} }
本節改以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); } }
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); } }
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); } }); } }