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.
No comments:
Post a Comment