// File: TwoButton2.java (Module 10) // // Author: Rahul Simha // Created: November 2, 2000 // // Two button example - with local classes import java.awt.*; import javax.swing.*; import java.awt.event.*; class NewFrame extends JFrame implements ActionListener { // Data. JButton quitB; // Quit button. JButton helloB, worldB; // Two silly buttons. // Constructor. public NewFrame (int width, int height) { // Set the title and other frame parameters. this.setTitle ("Two canvas example"); this.setResizable (true); this.setSize (width, height); // We'll use a flowlayout Container cPane = this.getContentPane(); cPane.setLayout (new FlowLayout()); // Quit button quitB = new JButton ("Quit"); quitB.setBackground (Color.red); // Local class definition. class QuitActionListener implements ActionListener { public void actionPerformed (ActionEvent a) { System.exit (0); } } // Instantiate local class. QuitActionListener qListener = new QuitActionListener(); // Add the listener to the button. quitB.addActionListener (qListener); // Finally, add the button to the frame. cPane.add (quitB); // "Hello" button helloB = new JButton ("Hello"); helloB.setBackground (Color.green); helloB.addActionListener (this); cPane.add (helloB); // "World" button worldB = new JButton ("World"); worldB.setBackground (Color.green); worldB.addActionListener (this); cPane.add (worldB); // Show the frame. this.setVisible (true); } // Need this method for the ActionListener interface. public void actionPerformed (ActionEvent a) { // Get the button string. String s = a.getActionCommand(); if (s.equalsIgnoreCase ("Quit")) System.out.println ("This case cannot occur"); else if (s.equalsIgnoreCase ("Hello")) { System.out.print ("Hello "); } else if (s.equalsIgnoreCase ("World")) { System.out.println ("World!"); } } } // End of class "NewFrame" public class TwoButton2 { public static void main (String[] argv) { NewFrame nf = new NewFrame (300, 200); } }