Java Applet with Programming examples

Description:

Java Applet with Programming Example:- In this article, I am going to show you how to use the applet in java with step-by-step programming examples.


From Java frame to Java applet:

Let us remember how I wrote the first simple program which prints text on the window. The program is given below or you can visit my article for learning more about font, style, and size in java.

The Testing class inherits from JFrame. In your constructor is first determines the reference to the content pane (the actual container of the frame). Then the layout of the container is determined. Finally, will an object of the JLabel class is created with the text to be displayed and the Container added. In the main method, there is an instance of the class Testing generates the caption of the title bar and the size of the frame determined, the frame made visibly and finally ensured that the window can be closed properly.

After compiling, we were able to use our program with the Java interpreter start by giving the command

Java Applet



Do we want the same functionality not in a frame, but in a java applet realize, we have to proceed a little differently:

Our Testing class now inherits from JApplet and thus becomes equipped with the prefabricated properties of a java applet. Like our Frame class, we also use the instance variable c of type in the java applet Container and labeling of the JLabel type.

Since our Java program is not responsible for creating an object in our java applet class we do not need to program a constructor. Building our simple graphical interface that is still housed in the constructor for the frame was, is used in our java applet class in the init method – which is automatic later is called when the java applet starts – relocated. Again (as with the Frame) the reference to the content pane determines the layout of the container and an object of the JLabel class is created with the text to be displayed and added to the container.

The most striking difference to our frame class is certainly the lack of the main method. Our class Testing can therefore after compiling also cannot be started directly with the Java interpreter do a little more.


Embed java applet in HTML file:

In order to actually make our java applet executable, we need the class first in an HTML page such as

Save the file in Testing.html. Generally seen, the page description language HTML is used to define the Content, structure, and format of texts and images on websites on the Internet should be displayed. For this purpose, so-called tags in the form of keywords, each bracketed by < and > are used. These tags mark the beginning and the end (which contain tags then a preceding / character) of a section of text that refers to a specific type is to be represented. For example, <b> directs you in bold appearing text section and </b> terminate it.

In addition, there is an HTML file, each complete with the tag <html> starts and ends with </html>, usually from ahead (between <head> and </head>), for example a title (between <title> and </title>) and a body (between <body> and </body>) that contains the actual text and image content of the document (in our example especially the applet). In addition, the language HTML provides, by the way not like Java differentiates between upper and lower case, of course, An extensive range of tags are available.  In the above Incidentally, we have also used the <hr> tag, which is a horizontal tag Line draws.

For us, as java applet programmers, a very special HTML tag is crucial, the applet tag <applet …> in line 12. This is responsible for the call our java applet and requires additional information, so-called attributes, namely

  • code = “Testing.class”

specifies the name of the Java applet class to be executed.

  • width = “500”

defines the width of the java applet area in pixels.

  • height = “300”

defines the height of the java applet area in pixels.

Should the applet not run in a web browser due to an error only the text between <applet …> and </applet> is displayed (line 13). Part of what we have in the frame example programmed in the main method is now in our java applet within the applet tag of the HTML file.


Execute java applet via HTML file:

Now we are able to run our applet. We will use first the applet viewer, a utility program that is included in every JDK installation. Let’s give the command in a console window

Java Applet

a window is created in which the java applet can be displayed. In our java applet is now displayed in this window (see above Figure) – and only the applet, the rest of the content of the HTML file is ignored. The complete content of our HTML file can only be accessed by an Internet Browser such as google chrome or Microsoft Internet Explorer can be displayed.

To do this, we have to cause the browser of our choice to read the HTML file to open. This can be done e.g. via its file menu and the entry ”Page Open “or by double-clicking on the HTML file.

Java Applet

The displayed Page (see in below figure) will now be exactly between the two horizontal ones Lines that we inserted into our HTML page with the two <hr> tags reserved the area specified in the applet tag for the applet and this displayed there.

Java Applet

 JApplet class Methods:

If you look at the hierarchy of the AWT and Swing classes, you can see that the JApplet class is exactly like JFrame and other swing components from the AWT Component classes and inherits the container. Thus, of course, like all other components the methods described in my previous article which is mention above, for each JApplet object getBackground, setBackground, getForeground, setForeground getFont, setFont, getHeight, getWidth, and setSize, add, remove, getComponents and setLayout is available with the corresponding functionality. Beyond that are of course also inherited methods addXxxListener and removeXxxListener for registering listener objects.

Just like a JFrame object, a JApplet object can also use the Content pane on which components can be inserted, one of its own Get menu bar. This is why the JApplet class also provides the instance methods getContentPane and setJMenuBar ready.

The JApplet class inherits important methods from the Applet class, with the init, start, stop and destroy methods are of particular importance. These are automatically used by the applet viewer or browser Communication with the applet called, depending on the status.


Methods of Japplet:

public void init():

public void init() is called when the applet is first loaded and is used for initialization of the applet object (as a substitute, so to speak, for corresponding instructions in a constructor).

public void start():

public void start() is called when the java applet is started (immediately after init and every time the HTML page in which the applet is embedded is displayed again becomes).

public void stop():

public void stop() is called when the java applet is temporarily stopped (every Time when the HTML page in which the applet is embedded is no longer displayed will, and immediately before destroy).

public void destroy():

public void destroy() is called when the java applet is destroyed (because the applet viewer or the browser is closed).

Java Applet Embedding in HTML:

Here, we want to briefly cover a few details on embedding an applet in HTML pages. On the one hand, we will focus on the Take a closer look at the java applet tag and, on the other hand, know a method to learn to set the page displayed by the browser.

java applet Tag:

In addition to width and height, we only have the attribute in the java applet tag code used to specify the applet class to run. In order for the applet to work, it must be in the same directory like the HTML file. If you want the applet in a different directory the codebase attribute can be used to specify the path to specify for java applet. Such a path specification can be absolutely in the form of a Complete web address or relative to the directory in which the HTML page save.

If an java applet works with many different classes, what happens with a larger one Programming project can be the case, in principle all of them must of course these classes can be downloaded from the Internet as required. In such cases it is a good idea to first combine all of these classes in an archive file. Every JDK installation offers a tool called jar.

When embedding such applets The archive attribute can be used to add this archive file to the HTML file. be adorned. This allows the compressed Transferring archive files over the Internet, which of course is less laborious is as the transmission of the individual classes in uncompressed form. Started the applet identified by the code attribute is then as usual, whose bytecode the interpreter can read out directly from the archive file.

For example, if we have the three compiled class files (the applet class Connects PointsApplet.class, the panel class DrawingBoard.class and the listener class drawingBoard_ClickEditor.class), which are in our Applet PointsConnectingApplet are needed in an archive called pva.jar and let’s not put the archive file in the directory in where the HTML file is located, but in the basement subdirectory, so must the HTML file have the following form:

We cannot switch between the two tags <applet …> and </applet> write the only text that the browser displays instead of the applet in the event of an error. We can also configure any parameters here – however always displayed as strings to the applet ¨.



How to use parameters in java applet:

The HTML tag <param …> is used to repeat the attributes name and value to set the name and value of a parameter In the HTML file.

for example, in lines 9 to 13 we put the five parameters north, east, south, west, and center fixed with the string values ​​North, East, South, West, and Center.

Within the embedded applet, the values ​​of these parameters can be accessed using the method

  • public String getParameter (String name)

returns the value of the parameter with name from the parameter list within of the two applet tags that embed the applet in the HTML page.

can be read out In the Testing applet, the Form getParameter (“north”) I return the character string. For example, if we want to ensure in our Testing class, that the five parameters for labeling the five regions of a border layout are used, we could proceed as follows:

Java Applet

In the instance variable param (a field with components of the string type) we have first determined the names of the parameters that are taken from the HTML file that Should be adopted. Have in another field called place We also store the corresponding “cardinal points” of the border layout. So if we deal with param[i], we know that the current value of this parameter is stored in the ort[i] area of ​​the border layout shall be. In the init method, we can therefore each use a loop to determine the value of the i-th parameter with getParameter and this Use add to place it as a label in the ort[i] area. With the parameters of the above HTML file result in the labeling shown in the above Figure.


showDocument method in Java applet:

An java applet is able to set up the browser in which it is currently running load and display another website. The applet is required for this Of course, access to the surrounding context (the web browser or applet viewer, who runs the applet). The method is therefore in the JApplet class

  • public AppletContext getAppletContext():

provides a reference to the applet context.

available AppletContext is an interface that, among other things, supports the method

  • public void showDocument (URL url):

initiates the browser environment specified by the url Internet page display. If the applet context is not a browser, the Method call is ignored.

To use this method, we need the address of the website to be displayed in the form of a URL object. Under one URL (Uniform Resource Locator) is a special representation of an Internet address. It defines exactly which file from which computer with which Service should be called. At the moment we want under url just understand what we usually use as a web address, though we go to a certain page on the internet with our browser. We want to display a specific web page with the showDocument method we can use the constructor

  • public URL (String spec) throws MalformedURLException

creates a URL from the specified string representation spec.

the URL class provided in the java.net package is simply a URL object create, however, you have to note that the constructor is a special exception is thrown if the specified character string is not formally is valid as a URL Using these methods, we have our sample java applet code is

And HTML code is

Now compile the code and open the Testing.html file in web browser

Java Applet

Java Applet

When you click the open website button the website will be opened as you can see in the below figure

Java Applet


How to enable Java Applet in Web Browser:

If the java applet is not displayed in your google chrome or Microsoft Internet Explorer browser, this may be because that your browser is not running the current version of the Java runtime system is working. You can easily fix this by using the appropriate Java plug-in activates. Simply open the Microsoft internet explorer browser

Java Applet

Then click on setting and then select the internet option.

Java Applet

After clicking the internet option a new window will be opened in this window select the Security tab and click on a custom level.

Java Applet

After clicking the custom level button a new window will be opened again in this window search scripting of java applets in the list and enabled and press the ok button

Java Applet


Java Applet Example:

How to change the color of the top panel with a button using java applet:

Here is an example of an applet that creates:

  • a panel that is added to the content, without parameters: it is therefore placed in the “central” area of the container (remember that the default handler for JApplet is of type BorderLayout);
  • a second panel that is placed at the bottom (“South” parameter) and in which we incorporate two buttons allowing to act on the color of the top panel.

It is preceded by the HTML file required to launch the applet, and accompanied by a example of execution obtained with an applet viewer.

Html code:

Java code:

Output:

Java Applet

Java Applet

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

2 Comments

Leave a Reply

%d bloggers like this: