The applet described in the previous section was a subclass of java.applet.Applet and as such did not use any Swing features. The advantage of this is that the applet can be invoked by any Java 1.0–enabled Web browser (virtually all browsers). The disadvantage is that we are restricted to the limited AWT graphical user interface. Applets can use the Swing features described earlier in this chapter. However, most browsers such as Microsoft Internet Explorer or Netscape Navigator that support only Java version 1.1 can run version 1.2 or Swing applets if they install a Java 1.2 plugin. However, if we use a plugin, we cannot use the >APPLET< tag in an HTML page. The tags that are used are more complex and differ from browser to browser; however, Sun does provide a utility for converting an >APPLET< tag to the plugin equivalent. The next listing shows the Swing version of the MultiplyApplet example.
Figure : Internet Explorer invoking Multiply Applet.
MultiplyApplet—Swing version
import javax.swing.*;
import java.awt.Container;
public class MultiplyApplet extends JApplet
{
private String param1;
private String param2;
private String resultString;
private int arg1;
private int arg2;
private int result;
Container cp;
public void init()
{
param1 = getParameter(''firstInt");
param2 = getParameter("secondInt");
arg1 = Integer.parseInt(param1);
arg2 = Integer.parseInt(param2);
result = arg1 * arg2;
cp = getContentPane();
Panel p = new Panel ();
cp.add(p);
}
class Panel extends JPanel
{
public void paintComponent (java.awt.Graphics g)
{
super.paintComponent(g);
resultString = Integer.toString(result);
g.drawString("The product of " + param1 + " and " + param2 + " is " + resultString, 50, 100);
}
}
}
There are only a couple of differences between the Swing and AWT versions. The first point to note is that our Multiply applet is a subclass of JApplet and not Applet. The JApplet class is actually a subclass of Applet and consequently inherits many of its methods. The second difference is that we do not draw the result directly on to the applet but create a JPanel subclass, Panel, and use the subclass paintComponent method to draw the result. This technique was described in Section 8.8. Panel is another example of an inner class. We could have declared Panel as a separate, outer, class. However, in that case, Panel would not have had access to MultiplyApplet's member variables, such as result, unless we declared these public. Note that we still use the AWT Graphics object in Swing. We can use the Multiply.html page to run this applet.
Swing Applets
Tags
# Developing GUIs
# Swing Applets
Share This
Swing Applets
Labels:
Developing GUIs,
Swing Applets
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment