7
Capturer les événements sur une fenêtre
- import java.awt.Frame;
- import java.awt.event.*;
- public class SimpleWindow1 {
- static ApplicationWindow appwin;
- public static void main(String[] args) {
- appwin = new ApplicationWindow("Application");
- appwin.addWindowListener(appwin);
- appwin.setBounds(100, 100, 300, 200);
- appwin.setVisible(true);
- }
- }
- @SuppressWarnings("serial")
- class ApplicationWindow extends Frame implements WindowListener {
- ApplicationWindow(String s) {
- super(s);
- }
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- public void windowActivated(WindowEvent e) {
- System.out.println("Activated");
- }
- public void windowClosed(WindowEvent e) {
- System.out.println("Closed");
- }
- public void windowDeactivated(WindowEvent e) {
- System.out.println("Deactivated");
- }
- public void windowDeiconified(WindowEvent e) {
- System.out.println("Deiconified");
- }
- public void windowIconified(WindowEvent e) {
- System.out.println("Iconified");
- }
- public void windowOpened(WindowEvent e) {
- System.out.println("Opened");
- }
- }
Compilez et exécutez le programme puis cliquez à l'extérieur et l'intérieur de la fenêtre, réduisez-la et restaurez-la. Tous ces événements sont capturés et tracés par le programme. Pour quitter le programme, choisissez Fermer dans le menu du gestionnaire de fenêtres.
$ javac SimpleWindow1.java
$ java SimpleWindow1
Opened
Activated
Deactivated
Activated
Deactivated
Iconified
Deiconified
Activated
...
- import java.awt.Frame;
- import java.awt.event.*;
- public class SimpleWindow2 implements WindowListener {
- static Frame appwin;
- public static void main(String[] args) {
- appwin = new Frame("Application");
- appwin.addWindowListener(new SimpleWindow2());
- appwin.setBounds(100, 100, 300, 200);
- appwin.setVisible(true);
- }
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- public void windowActivated(WindowEvent e) {
- System.out.println("Activated");
- }
- public void windowClosed(WindowEvent e) {
- System.out.println("Closed");
- }
- public void windowDeactivated(WindowEvent e) {
- System.out.println("Deactivated");
- }
- public void windowDeiconified(WindowEvent e) {
- System.out.println("Deiconified");
- }
- public void windowIconified(WindowEvent e) {
- System.out.println("Iconified");
- }
- public void windowOpened(WindowEvent e) {
- System.out.println("Opened");
- }
- }
Commentaires