/home/wpollock1/public_html/Java/EventDemo.java
/* This simple AWT Frame changes its background color when its button
* is clicked. Although simple it illustrates all the basic tasks of
* creating a GUI program. See EventDemoSwing.java for a Swing version;
* it's very similar.
*
* Written 2016 by Wayne Pollock, Tampa Florida USA. All Rights Reserved.
*/
import java.awt.*;
import java.awt.event.*;
public class EventDemo extends Frame {
public static void main ( String[] args ) {
// Create objects and initialize their properties:
EventDemo demo = new EventDemo();
demo.setTitle( "Event Demo - AWT Version" );
demo.setSize( 380, 200 );
demo.setLayout( new FlowLayout() );
demo.setLocationRelativeTo( null ); // Center on the screen.
demo.setBackground( Color.YELLOW );
Button btn = new Button( "Change color" );
// Add objects to user interface (and position them):
demo.add( btn );
// Hook up event handlers:
btn.addActionListener( ae -> {
if ( demo.getBackground() == Color.YELLOW )
demo.setBackground( Color.CYAN );
else
demo.setBackground( Color.YELLOW );
}
);
// Set window closing action:
demo.addWindowListener( new WindowAdapter() {
public void windowClosing ( WindowEvent we ) {
System.exit( 0 );
}
}
);
demo.setVisible( true );
}
}
/* Note before Java 8 added Lambda notation, the event handling would be this:
btn.addActionListener( new ActionListener () {
public void actionPerformed ( ActionEvent ae ) {
if ( getBackground() == Color.YELLOW )
setBackground( Color.CYAN );
else
setBackground( Color.YELLOW );
}
}
);
An alternative is to define a new public void method like this:
public void doClick ( ActionEvent ae ) { ... }
Then you can use a method reference in the constructor instead
of a lambda, like this:
btn.addActionListener ( this::doClick );
*/