/* NestedButtonTest.java * * Illustrates the use of background coloring and nested * components. * * Derived from Example 6-1 in * "Java Examples in a Nutshell", David Flanagan, * O'Reilly & Associates, 1997 * * Frame -- panel1 -- button1 * | | * | |-- panel2 -- button2 * | | * | |-- panel3 -- button3 * | | * | |-- panel4 -- button4 * | | * |-- button6 |-- button5 * * March 29, 1998 */ import java.awt.*; import java.awt.event.*; import corejava.*; public class NestedButtonTest extends CloseableFrame implements ActionListener { public static void main( String[] args ) { NestedButtonTest f = new NestedButtonTest(); f.show(); } public NestedButtonTest() { setLayout( new FlowLayout() ); this.setBackground( Color.white ); this.setFont( new Font( "Dialog", Font.BOLD, 24 ) ); // Create buttons and register them Button redButton = new Button( "Red" ); Button orangeButton = new Button( "Orange" ); Button yellowButton = new Button( "Yellow" ); Button greenButton = new Button( "Green" ); Button blueButton = new Button( "Blue" ); Button magentaButton = new Button( "Magenta" ); Panel p1 = new Panel(); p1.add( redButton ); p1.setBackground( Color.red ); this.add( p1 ); redButton.addActionListener( this ); Panel p2 = new Panel(); p2.add( orangeButton ); p2.setBackground( Color.orange ); p1.add( p2 ); orangeButton.addActionListener( this ); Panel p3 = new Panel(); p3.add( yellowButton ); p3.setBackground( Color.yellow ); p2.add( p3 ); yellowButton.addActionListener( this ); Panel p4 = new Panel(); p4.add( greenButton ); p4.setBackground( Color.green ); p1.add( p4 ); greenButton.addActionListener( this ); Panel p5 = new Panel(); p5.add( blueButton ); p5.setBackground( Color.blue ); p1.add( p5 ); blueButton.addActionListener( this ); Panel p6 = new Panel(); p6.add( magentaButton ); p6.setBackground( Color.magenta ); this.add( p6 ); magentaButton.addActionListener( this ); } public void actionPerformed( ActionEvent e ) { Color c = Color.black; String arg = e.getActionCommand(); // Set color based upon button pressed if( arg.equals("Red" ) ) c = Color.red; else if( arg.equals("Orange" ) ) c = Color.orange; else if( arg.equals("Yellow" ) ) c = Color.yellow; else if( arg.equals("Green" ) ) c = Color.green; else if( arg.equals("Blue" ) ) c = Color.blue; else if( arg.equals("Magenta" ) ) c = Color.magenta; setBackground( c ); repaint(); } }