EventDemo.java

Download EventDemo.java

 1: /* This simple AWT Frame changes its background color when its button
 2:  * is clicked.  Although simple it illustrates all the basic tasks of
 3:  * creating a GUI program.  See EventDemoSwing.java for a Swing version;
 4:  * it's very similar.
 5:  *
 6:  * Written 2016 by Wayne Pollock, Tampa Florida USA.  All Rights Reserved.
 7:  */
 8: 
 9: import java.awt.*;
10: import java.awt.event.*;
11: 
12: public class EventDemo extends Frame {
13:    public static void main ( String[] args ) {
14:       // Create objects and initialize their properties:
15:       EventDemo demo = new EventDemo();
16:       demo.setTitle( "Event Demo - AWT Version" );
17:       demo.setSize( 380, 200 );
18:       demo.setLayout( new FlowLayout() );
19:       demo.setLocationRelativeTo( null );  // Center on the screen.
20:       demo.setBackground( Color.YELLOW );
21: 
22:       Button btn = new Button( "Change color" );
23: 
24:       // Add objects to user interface (and position them):
25:       demo.add( btn );
26: 
27:       // Hook up event handlers:
28:       btn.addActionListener( ae -> {
29:                if ( demo.getBackground() == Color.YELLOW )
30:                   demo.setBackground( Color.CYAN );
31:                else
32:                   demo.setBackground( Color.YELLOW );
33:             }
34:       );
35: 
36:       // Set window closing action:
37:       demo.addWindowListener( new WindowAdapter() {
38:           public void windowClosing ( WindowEvent we ) {
39:               System.exit( 0 );
40:           }
41:         }
42:       );
43: 
44:       demo.setVisible( true );
45:    }
46: }
47: 
48: /* Note before Java 8 added Lambda notation, the event handling would be this:
49: 
50:       btn.addActionListener( new ActionListener () {
51:             public void actionPerformed ( ActionEvent ae ) {
52:                if ( getBackground() == Color.YELLOW )
53:                   setBackground( Color.CYAN );
54:                else
55:                   setBackground( Color.YELLOW );
56:             }
57:          }
58:       );
59: 
60:    An alternative is to define a new public void method like this:
61: 
62:       public void doClick ( ActionEvent ae ) { ... }
63: 
64:    Then you can use a method reference in the constructor instead
65:    of a lambda, like this:
66: 
67:       btn.addActionListener ( this::doClick );
68: */