// Action buttons that do something. // Rewritten to use Swing and to alternately appear // and disappear by Mark Sheldon, March 2006. // Modified November 2006 by Mark Sheldon to create // a window to run in when run as an applet. import java.awt.*; import javax.swing.*; import java.util.*; import java.awt.event.*; // for ActionListener and ActionEvent public class TinmanButton extends JApplet implements ActionListener { private final String draw = "Draw"; private final String hide = "Hide"; private JButton drawOrHideButton; private OzCanvas ozCanvas; private JPanel controlPanel; private static JFrame appFrame; // When running as application public void init() { drawOrHideButton = new JButton(draw); // Draw first, Hide later drawOrHideButton.addActionListener(this); // register our interest ozCanvas = new OzCanvas(); // A place to draw ozCanvas.setVisible(false); // hide for now Container content = getContentPane(); content.setLayout(new BorderLayout()); content.add(drawOrHideButton, BorderLayout.SOUTH); // add button to applet window content.add(ozCanvas, BorderLayout.CENTER); } //Implement the ActionListener interface's actionPerformed() method. // This is the actual event-handling method. public void actionPerformed(ActionEvent event) { boolean newlyVisible = !ozCanvas.isVisible(); ozCanvas.setVisible(newlyVisible); drawOrHideButton.setText( newlyVisible ? hide : draw); } // The following is needed to embed the applet in an application. public static void main (String[] args) { // final JFrame frame = new JFrame("Frame for Tinman Applet"); appFrame = new JFrame("Frame for Tinman Applet"); TinmanButton tinman = new TinmanButton(); appFrame.setSize(725, 600); appFrame.getContentPane().add("Center", tinman); appFrame.addWindowListener(new AppFrameCloser(appFrame)); tinman.init(); appFrame.show(); } } class OzCanvas extends JPanel { public void paintComponent(Graphics g) { g.setColor(Color.red); g.drawOval(100,100,50,50); // Head Polygon hat = new Polygon(); hat.addPoint(100,100); hat.addPoint(125,70); hat.addPoint(150,100); g.fillPolygon(hat); g.drawString("If I only had a brain", 80, 60); g.fillRect(100,150,50,80); // Body g.fillRect(105,230,15,50); // Leg g.fillRect(130,230,15,50); // Leg g.fillRect(75,175,100,20); // Arms } } class AppFrameCloser extends WindowAdapter { private JFrame frame; public AppFrameCloser(JFrame frame) { this.frame = frame; } public void windowClosing(WindowEvent e) { frame.dispose(); } }