Program: AppletViewer

Another JDK tool that can be replicated is the AppletViewer. This uses the reflection package to load a class that is subclassed from Applet, instantiate an instance of it, and add( ) this to a frame at a given size. This is a good example of reflection in action: you can use these techniques to dynamically load any subclass of a given class. Suppose we have a simple applet like the HelloApplet in Example 25-11.

Example 25-11. HelloApplet.java

import java.applet.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; /** * HelloApplet is a simple applet that toggles a message * when you click on a Draw button. */ public class HelloApplet extends JApplet { /** The flag which controls drawing the message. */ protected boolean requested; /** init( ) is an Applet method called by the browser to initialize */ public void init( ) { JButton b; requested = false; Container cp = (Container)getContentPane( ); cp.setLayout(new FlowLayout( )); cp.add(b = new JButton("Draw/Don't Draw")); b.addActionListener(new ActionListener( ) { /* Button - toggle the state of the "requested" flag, to draw or * not to draw. */ public void actionPerformed(ActionEvent e) { String arg = e.getActionCommand( ); // Invert the state of the draw request. requested = !requested; do_the_work( ); } }); } /** paint( ) is an AWT Component method, called when the * component needs to be painted. */ public void do_the_work( ) { /* If the Draw button is selected, draw something */ if ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.