< Prev
Next >

Paint() method in Applet

In this article, we are going to understand how to print a message in the applet window by implementing a method paint() of the Applet class. Within the method paint() we will call drawString() method to print a text message in the applet window.

when the paint() method is invoked?

Method paint() is automatically called whenever there is a need to display the applet window, this need could arise in certain situations -

Signature of paint() method

public void paint(Graphics g)
The method paint() gives us an access to an object of Graphics class type in our applet code. Using the object of Graphics class, we can call drawString() method of Graphics class to write a text message in the applet window.

Signature of drawString() method

public void drawString(String, int x, int y)
The method drawString() takes a String which will be printed on applet window, starting from left-top corner at the coordinates x and y.

  • Writing a message on applet window.

  • import java.awt.*;
    import java.applet.*;
    <applet  code="Applet24" width=400 height=200>
    public class Applet24 extends Applet
    String str ="";
    public void init()
    public void start()
    public void stop()
    public void paint(Graphics g)
    g.drawString("Hello from the Applet.", 40,40);
    g.drawString("How are you doing?", 40, 60);
    g.drawString("We wish you a pleasant day today.", 40, 80);

    In order to run our applet using appletviewer, type the following command at command prompt-

    appletviewer Applet24.java

    Where Applet24.java is the name of java file that contains the code of an applet.


    Right after running the applet program using appletviewer a new applet window is displayed to us -

    Figure 1

    As the applet began its execution for the first time-

    Now, when the applet window screen is minimized and brought up again, the next applet window looks like this-

    Figure 2

    As you may see in the Figure 2 of applet window-

    Please Subscribe

    Please subscribe to our social media channels for daily updates.

    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page