Examples for java applets

Essentials, Part 1, Lesson 3: Building Applets

Like applications, applets are created from classes. However, applets do not have a main method as an entry point, but instead, have several methods to control specific aspects of applet execution.

This lesson converts an application from Lesson 2 to an applet and describes the structure and elements of an applet.

Contents

Application to Applet

The following code is the applet equivalent to the LessonTwoB application from Lesson 2. The figure below shows how the running applet looks. The structure and elements of the applet code are discussed after the section on how to run the applet just below.

 import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; public class SimpleApplet extends Applet < String text = "I'm a simple applet"; public void init() < text = "I'm a simple applet"; setBackground(Color.cyan); >public void start() < System.out.println("starting. "); >public void stop() < System.out.println("stopping. "); >public void destroy() < System.out.println("preparing to unload. "); >public void paint(Graphics g) < System.out.println("Paint"); g.setColor(Color.blue); g.drawRect(0, 0, getSize().width -1, getSize().height -1); g.setColor(Color.red); g.drawString(text, 15, 25); >> 

The SimpleApplet class is declared public so the program that runs the applet (a browser or appletviewer ), which is not local to the program can access it.

Run the Applet

To see the applet in action, you need an HTML file with the Applet tag as follows:

Читайте также:  Python on web tutorial

The easiest way to run the applet is with appletviewer shown below where simpleApplet.html is a file that contains the above HTML code:

Note: To run an applet written with Java 2 APIs in a browser, the browser must be enabled for the Java 2 Platform. If your browser is not enabled for the Java 2 Platform, you have to use appletviewer to run the applet or install Java Plug-in. Java Plug-in lets you run applets on web pages under the 1.2 version of the Java VM instead of the web browser’s default Java VM.

Applet Structure and Elements

The Java API Applet class provides what you need to design the appearance and manage the behavior of an applet. This class provides a graphical user interface (GUI) component called a Panel and a number of methods. To create an applet, you extend (or subclass) the Applet class and implement the appearance and behavior you want.

The applet’s appearance is created by drawing onto the Panel or by attaching other GUI components such as push buttons, scrollbars, or text areas to the Panel . The applet’s behavior is defined by implementing the methods.

Extending a Class

Most classes of any complexity extend other classes. To extend another class means to write a new class that can use the fields and methods defined in the class being extended. The class being extended is the parent class, and the class doing the extending is the child class. Another way to say this is the child class inherits the fields and methods of its parent or chain of parents. Child classes either call or override inherited methods. This is called single inheritance.

The SimpleApplet class extends Applet class, which extends the Panel class, which extends the Container class. The Container class extends Object , which is the parent of all Java API classes.

The Applet class provides the init , start , stop , destroy , and paint methods you saw in the example applet. The SimpleApplet class overrides these methods to do what the SimpleApplet class needs them to do. The Applet class provides no functionality for these methods.

However, the Applet class does provide functionality for the setBackground method,which is called in the init method. The call to setBackground is an example of calling a method inherited from a parent class in contrast to overriding a method inherited from a parent class.

You might wonder why the Java language provides methods without implementations. It is to provide conventions for everyone to use for consistency across Java APIs. If everyone wrote their own method to start an applet, for example, but gave it a different name such as begin or go , the applet code would not be interoperable with other programs and browsers, or portable across multiple platforms. For example, Netscape and Internet Explorer know how to look for the init and start methods.

An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be appletviewer as you saw in the example. The underlying software controls the applet by calling the methods the applet inherits from the Applet class.

The init Method: The init method is called when the applet is first created and loaded by the underlying software. This method performs one-time operations the applet needs for its operation such as creating the user interface or setting the font. In the example, the init method initializes the text string and sets the background color.

The start Method: The start method is called when the applet is visited such as when the end user goes to a web page with an applet on it. The example prints a string to the console to tell you the applet is starting. In a more complex applet, the start method would do things required at the start of the applet such as begin animation or play sounds.

After the start method executes, the event thread calls the paint method to draw to the applet’s Panel . A thread is a single sequential flow of control within the applet, and every applet can run in multiple threads. Applet drawing methods are always called from a dedicated drawing and event-handling thread.

The stop and destroy Methods: The stop method stops the applet when the applet is no longer on the screen such as when the end user goes to another web page. The example prints a string to the console to tell you the applet is stopping. In a more complex applet, this method should do things like stop animation or sounds.

The destroy method is called when the browser exits. Your applet should implement this method to do final cleanup such as stop live threads.

The Panel provided in the Applet class inherits a paint method from its parent Container class. To draw something onto the Applet’s Panel , you implement the paint method to do the drawing.

The Graphics object passed to the paint method defines a graphics context for drawing on the Panel . The Graphics object has methods for graphical operations such as setting drawing colors, and drawing graphics, images, and text.

The paint method for the SimpleApplet draws the I’m a simple applet string in red inside a blue rectangle.

 public void paint(Graphics g) < System.out.println("Paint"); //Set drawing color to blue g.setColor(Color.blue); //Specify the x, y, width and height for a rectangle g.drawRect(0, 0, getSize().width -1, getSize().height -1); //Set drawing color to red g.setColor(Color.red); //Draw the text string at the (15, 25) x-y location g.drawString(text, 15, 25); > 

Packages

The applet code also has three import statements at the top. Applications of any size and all applets use import statements to access ready-made Java API classes in packages. This is true whether the Java API classes come in the Java platform download, from a third-party, or are classes you write yourself and store in a directory separate from the program. At compile time, a program uses import statements to locate and reference compiled Java API classes stored in packages elsewhere on the local or networked system. A compiled class in one package can have the same name as a compiled class in another package. The package name differentiates the two classes.

The examples in Lessons 1 and 2 did not need a package declaration to call the System.out.println Java API class because the System class is in the java.lang package that is included by default. You never need an import java.lang.* statement to use the compiled classes in that package.

More Information

You can find more information on applets in the Writing Applets trail in The Java Tutorial.

Источник

Developing an Applet

An application designed using component-based architecture can be developed into a Java applet. Consider the example of a Java applet with a Swing-based graphical user interface (GUI). With component-based design, the GUI can be built with smaller building blocks or components. The following general steps are used to create an applet GUI:

  • Create a class MyTopJPanel that is a subclass of javax.swing.JPanel . Lay out your applet’s GUI components in the constructor of the MyTopJPanel class.
  • Create a class called MyApplet that is a subclass of javax.swing.JApplet .
  • In the init method of MyApplet , instantiate MyTopJPanel and set it as the applet’s content pane.

The following sections explore these steps in greater detail by using the Dynamic Tree Demo applet. If you are not familiar with Swing, see Creating a GUI with Swing to learn more about using Swing GUI components.

Note: If you don’t see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.

Creating the Top JPanel Class

Create a class that is a subclass of JPanel . This top JPanel acts as a container for all your other UI components. In the following example, the DynamicTreePanel class is the topmost JPanel . The constructor of the DynamicTreePanel class invokes other methods to create and lay out the UI controls properly.

public class DynamicTreePanel extends JPanel implements ActionListener < private int newNodeSuffix = 1; private static String ADD_COMMAND = "add"; private static String REMOVE_COMMAND = "remove"; private static String CLEAR_COMMAND = "clear"; private DynamicTree treePanel; public DynamicTreePanel() < super(new BorderLayout()); //Create the components. treePanel = new DynamicTree(); populateTree(treePanel); JButton addButton = new JButton("Add"); addButton.setActionCommand(ADD_COMMAND); addButton.addActionListener(this); JButton removeButton = new JButton("Remove"); // . JButton clearButton = new JButton("Clear"); // . //Lay everything out. treePanel.setPreferredSize( new Dimension(300, 150)); add(treePanel, BorderLayout.CENTER); JPanel panel = new JPanel(new GridLayout(0,3)); panel.add(addButton); panel.add(removeButton); panel.add(clearButton); add(panel, BorderLayout.SOUTH); >// . >

Creating the Applet

For a Java applet that has a Swing-based GUI, create a class that is a subclass of javax.swing.JApplet . An applet that does not contain a Swing-based GUI can extend the java.applet.Applet class.

Override the applet’s init method to instantiate your top JPanel class and create the applet’s GUI. The init method of the DynamicTreeApplet class invokes the createGUI method in the AWT Event Dispatcher thread.

package appletComponentArch; import javax.swing.JApplet; import javax.swing.SwingUtilities; public class DynamicTreeApplet extends JApplet < //Called when this applet is loaded into the browser. public void init() < //Execute a job on the event-dispatching thread; creating this applet's GUI. try < SwingUtilities.invokeAndWait(new Runnable() < public void run() < createGUI(); >>); > catch (Exception e) < System.err.println("createGUI didn't complete successfully"); >> private void createGUI() < //Create and set up the content pane. DynamicTreePanel newContentPane = new DynamicTreePanel(); newContentPane.setOpaque(true); setContentPane(newContentPane); >>

Benefits of Separating Core Functionality From the Final Deployment Mechanism

Another way to create an applet is to just remove the layer of abstraction (separate top JPanel ) and lay out all the controls in the applet’s init method itself. The downside to creating the GUI directly in the applet is that it will now be more difficult to deploy your functionality as a Java Web Start application, if you choose to do so later.

In the Dynamic Tree Demo example, the core functionality resides in the DynamicTreePanel class. It is now trivial to drop the DynamicTreePanel class into a JFrame and deploy as a Java Web Start application.

Hence, to preserve portability and keep deployment options open, follow component-based design as described on this page.

Download source code for the Dynamic Tree Demo Applet example to experiment further.

Источник

Applet Development Examples

The following table lists all the examples in the Applets lesson. The first column shows the name of the example. Click on the name of the example to launch the applet. The second column shows a link to a zip file with complete source code. You can open and run the examples in the NetBeans IDE. See Running Tutorial Examples in NetBeans IDE for more information. The third column has a link to the Java Tutorials topic where the example is described in detail.

Example
(click on link to view example)
Zip File
(contains all source files necessary for the example plus NetBeans IDE project metadata)
Where Described
Applet With Parameters applet_AppletWithParameters Defining and Using Applet Parameters
DOM Dump applet_TraversingDOM Manipulating DOM of Applet’s Web Page
Draggable Applet applet_Draggable Developing Draggable Applets
Dynamic Tree Demo Applet applet_ComponentArch_DynamicTreeDemo Developing an Applet
Deploying an Applet
Hello World applet_HelloWorld Getting Started With Applets
Invoking Applet Methods From JavaScript Code applet_InvokingAppletMethodsFromJavaScript Invoking Applet Methods From JavaScript Code
Invoking JavaScript Code From Applet applet_InvokingJavaScriptFromApplet Invoking JavaScript Code From an Applet
Sender Receiver Applets applet_SenderReceiver Communicating With Other Applets
Show Document applet_ShowDocument Displaying Documents in the Browser
Simple Applet applet_Simple Life Cycle of an Applet
Status and Event Handler applet_StatusAndCallback Handling Initialization Status With Event Handlers

The AppletTutorialExamples zip file contains the complete set of examples listed in the table.

Источник

Оцените статью