0

I am unable to understand why the println() statement inside paint() is executing twice.This is the code-

import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet
{
    public void init()
    {
        System.out.println(getBackground());
    }
    public void paint(Graphics g)
    {
        setBackground(Color.CYAN);
        setForeground(Color.RED);
        g.drawString("This is my first Applet",250,250);
        System.out.println(getBackground());
    }
}

OUTPUT:

java.awt.Color[r=255,g=255,b=255]

java.awt.Color[r=0,g=255,b=255]

java.awt.Color[r=0,g=255,b=255]

Can somebody please explain me why the println() inside paint() is executing twice?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42

1 Answers1

1
public void paint(Graphics g)
{
    setBackground(Color.CYAN);  // will trigger repaint()!
    setForeground(Color.RED);   // will trigger repaint()!
    g.drawString("This is my first Applet",250,250);
    System.out.println(getBackground());
}

The paint(Graphics) method is called whenever the toolkit feels it is necessary to do so. There are many things that will cause a repaint() (which in turn, leads to a call to paint(Graphics)). Some of them are:

  • A window moves in front of, or is removed from in front of, the app.
  • The size of the app. changes.
  • The background or foreground color changes or a component state changes.
  • A menu opens or closes.
  • ...

Obviously, a paint does not happen only the times the programmer wants (or expects) it to. If that 'paint whenever needed' is a problem for the app., it is the apps. problem to sort, not the toolkits.


Queries for you:

  1. Why code an applet? If it is due to the teacher specifying it, please refer them to Why CS teachers should stop teaching Java applets.
  2. Why use AWT? See this answer for many good reasons to abandon AWT using components in favor of Swing.
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433