Java Reference
In-Depth Information
Note that there are four methods in the MyApplet class. All four methods override
methods from the JApplet class. The init method is the first method that is called. Its
job is to initialize the local variables, get data from the user, and display different GUI
The same applet can be started and stopped multiple times. Every time the applet
starts, the start method is called. The start method is initially called immediately after
the init method. The start method will also be called if the web browser decides to restart
the applet. For example, consider a resource-intensive applet that displays 3D animation.
If the user navigates away from the applet's web page, then the web browser will stop the
applet. At this point, the stop method will be called. If the user navigates back to the web
page, then the start method will be called. In this case, the job of the start method will
be to resume the animation, while the job of the stop method will be to stop the animation.
Note that the stop method is also called just before the applet is terminated (e.g., the user
closes the web browser). The destroy method is called just before the applet is terminated
by the web browser.
Consider the above program. It creates a panel and adds it to the applet. The
paintComponent method of the panel displays the current value of i and the last method
that is called. Note that the value of i starts at 0 and is incremented by 1 every time one
of the four methods is called. As expected, our applet application does not have a main
method, methods that make the applet window visible, or methods that set the title or
size of the applet. All these parameters are specified from the HTML file. In NetBeans, one
can just select the applet file, right-click on it, and run it. NetBeans will emulate a web
browser and start the applet. NetBeans also automatically creates a .html file in the build
subdirectory of the project. We can launch this file from a web browser to see the look and
feel of our applet in different web browsers.
15.3 Creating Popup Windows
One may get the impression that a Java Applet is stuck inside a web browser. That
is, we cannot create our own windows, set their size, and so on. This is not the case. The
following code demonstrates how we can incorporate our Calculator program inside a web
browser. The applet launches the Calculator program in a new window.
import java .awt. event . ;
import javax . swing . ;
public class MyApplet extends JApplet
public void init() {
JButton calcButton = new JButton( "Calculator" );
final JFrame frame = new JFrame () ;
frame. setTitle( "Calculator" );
frame. setSize (200,200) ;
frame .add( new CalculatorPanel ()) ;
calcButton . addActionListener( new ActionListener ()
public void actionPerformed(ActionEvent e)
frame. setVisible (!frame. isVisible());
}} );
Search WWH ::

Custom Search