import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Button; import java.awt.Event; public class ButtonPressWithApplet extends Applet { // Create two buttons; the buttons are created here (instead of in the 'init' // method) so that they will be accessible from within the 'action' method private Button button1, button2; public void init() { // Note that using no layout (or a null layout) is considered by some to be // a bad idea; there are a variety of different types of layout managers // that can be used to avoid absolute positioning of elements; by specifying // the exact location of objects on an applet window, if the window is // resized by a user, or if the program is run on a computer with a lower // screen resolution, it's possible that not all of the elements will fit // (be visible) on the applet window this.setLayout(null); // Set the size and background color of the applet window this.setSize(400, 175); this.setBackground(Color.WHITE); // Set the first button's caption, position, size, font, and colors button1 = new Button("Button #1"); button1.setBounds(50, 25, 300, 50); button1.setBackground(Color.BLUE); button1.setForeground(Color.WHITE); button1.setFont(new Font("Arial", Font.BOLD, 24)); // Set up the second button button2 = new Button("Button #2"); button2.setBounds(50, 100, 300, 50); button2.setBackground(Color.RED); button2.setForeground(Color.WHITE); button2.setFont(new Font("Arial", Font.BOLD, 24)); // Add the buttons to the (null) layout (make them visible); notice that no // explicit 'paint' method is needed, since components know how to paint // themselves; when an applet is repainted, it calls not only its own // 'paint' method, but also the 'paint' methods for all of the components // that it contains this.add(button1); this.add(button2); } // Check to see if an action (event) has occurred public boolean action(Event event, Object object) { // Since the only event that can really occur here is a button press, check // to see which button was pressed by the user if (event.target == button1) { button1.setVisible(false); button2.setVisible(true); } else { button2.setVisible(false); button1.setVisible(true); } return true; } }