javaappletawtpaint

How to paint in a simple applet?


The following code is supposed to print

Inside init()--
Inside start()-- 
Inside paint().

But, it prints the last part inside paint() twice! Why is that?

public class SampleApplet extends Applet {

String msg;

@Override
public void init(){
    setBackground(Color.BLACK);
    setForeground(Color.yellow);
    msg = "Inside init()-- ";
  }

@Override 
public void start(){
    msg += "Inside start()-- ";
  }

@Override 
public void paint(Graphics g){
    msg += "Inside paint().";
    g.drawString(msg, 10, 30);
  }
}

Solution

  • Quoted from: Paint():

    the paint() method will be called as many times as necessary. If you put another window over your GUI then the paint() method will be called. If you then minimize that window and make your GUI visible again then the paint() method will be called again. And so on.

    So if you have something that is a problem if the paint() method is called more than once, you have done it wrong. Don't do it that way. The paint() method should only redraw its target from existing data, it should never have to do calculations to figure out what to paint.