// File: TwoButton5.java (Module 10) // // Author: Rahul Simha // Created: November 2, 2000 // // Two button example - using anonymous classes. import java.awt.*; import javax.swing.*; import java.awt.event.*; class NewFrame extends JFrame { // Data. JButton quitB; // Quit button. JButton helloB, worldB; // Two silly buttons. String helloStr = "Hello "; String worldStr = "World!"; // 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); // Create an implementation right in the method call: quitB.addActionListener ( new ActionListener() { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); cPane.add (quitB); // "Hello" button helloB = new JButton ("Hello"); helloB.setBackground (Color.green); helloB.addActionListener ( new ActionListener() { public void actionPerformed (ActionEvent a) { // Note: we are accessing top-level variable. System.out.print (helloStr); } } ); cPane.add (helloB); // "World" button worldB = new JButton ("World"); worldB.setBackground (Color.green); worldB.addActionListener ( new ActionListener() { public void actionPerformed (ActionEvent a) { System.out.print (worldStr); } } ); cPane.add (worldB); // Deal with mouse clicks. cPane.addMouseListener ( new MouseAdapter () { public void mouseClicked (MouseEvent m) { System.out.println ("Mouse click!"); } } ); // Show the frame. this.setVisible (true); } } // End of class "NewFrame" public class TwoButton6 { public static void main (String[] argv) { NewFrame nf = new NewFrame (300, 200); } }