EventDemoSwing.java

Download EventDemoSwing.java

 1: /* This simple Swing JFrame changes its background color when its button
 2:  * is clicked.  Although simple, it illustrates all the basic tasks of
 3:  * creating a GUI applet or program.  The event handling code would work
 4:  * nearly the same if AWT were used instead of swing; see EventDemo.java.
 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: import javax.swing.*;
12: 
13: public class EventDemoSwing extends JFrame {
14:    public static void main ( String[] args ) {
15:       // Create objects and initialize properties:
16:       EventDemoSwing demo = new EventDemoSwing();
17:       demo.setTitle( "Event Demo - Swing Version" );
18:       demo.setSize( 380, 200 );
19:       demo.setLocationRelativeTo( null );  // Center on the screen.
20: 
21:       final JPanel pnl = new JPanel();
22:       pnl.setOpaque( true );
23:       pnl.setBackground( Color.YELLOW );
24:       demo.add( pnl );
25: 
26:       final JButton btn = new JButton( "Change color" );
27: 
28:       // Add objects to window (and position them):
29:       pnl.add( btn );
30: 
31:       // Hook up event handlers:
32:       demo.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
33: 
34:       // Note that with Swing, an User Interface changes must be made on
35:       // the Event Dispatch Thread (EDT); AWT doesn't require that.
36:       btn.addActionListener( new ActionListener () {
37:             @Override
38:             public void actionPerformed ( ActionEvent ae ) {
39:                SwingUtilities.invokeLater( () -> {   // Run this code from EDT.
40:                      if ( pnl.getBackground() == Color.YELLOW )
41:                         pnl.setBackground( Color.CYAN );
42:                      else
43:                         pnl.setBackground( Color.YELLOW );
44:                    }  // End of Lambda Expression
45:                );  // End of invokeLater
46:             }
47:          }
48:       );  // End of addActionListener
49:       demo.setVisible( true );
50:    }
51: }