简体   繁体   中英

Query about applets in java

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM