/home/wpollock1/public_html/Java/EventDemoSwing.java
/* This simple Swing JFrame changes its background color when its button
* is clicked. Although simple, it illustrates all the basic tasks of
* creating a GUI applet or program. The event handling code would work
* nearly the same if AWT were used instead of swing; see EventDemo.java.
*
* Written 2016 by Wayne Pollock, Tampa Florida USA. All Rights Reserved.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDemoSwing extends JFrame {
public static void main ( String[] args ) {
// Create objects and initialize properties:
EventDemoSwing demo = new EventDemoSwing();
demo.setTitle( "Event Demo - Swing Version" );
demo.setSize( 380, 200 );
demo.setLocationRelativeTo( null ); // Center on the screen.
final JPanel pnl = new JPanel();
pnl.setOpaque( true );
pnl.setBackground( Color.YELLOW );
demo.add( pnl );
final JButton btn = new JButton( "Change color" );
// Add objects to window (and position them):
pnl.add( btn );
// Hook up event handlers:
demo.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// Note that with Swing, an User Interface changes must be made on
// the Event Dispatch Thread (EDT); AWT doesn't require that.
btn.addActionListener( new ActionListener () {
@Override
public void actionPerformed ( ActionEvent ae ) {
SwingUtilities.invokeLater( () -> { // Run this code from EDT.
if ( pnl.getBackground() == Color.YELLOW )
pnl.setBackground( Color.CYAN );
else
pnl.setBackground( Color.YELLOW );
} // End of Lambda Expression
); // End of invokeLater
}
}
); // End of addActionListener
demo.setVisible( true );
}
}