简体   繁体   中英

how does java paint() method work?

I was expecting this applet to write x=0 and x=10, but it didn't :

import java.applet.*;
import java.awt.*;
/*
   <applet code="deney1" width=300 height=100>
   </applet>
   */
public class deney1 extends Applet {
    int x=0; // current position
    public void paint(Graphics g) {
        g.drawString("x="+x, 0,20);
        x+=10;
        g.drawString("x="+x, 0,40);
        x+=1;
    }
}

What is going on here?

EDIT : It is proposed that my question is a possible duplicate of this one :

how is paint() running without being called in the main method?

This post tells me that the paint() method will run without being explicitly called. But this doesn't explain the order in which the statements in paint() are executed, and I can't track the printed x values. Why not 0 and 10? Why not 11 and 22? To make things a bit more clear :

g.drawString("x="+x, 0,20);     //  1
x+=10;                          //  2
g.drawString("x="+x, 0,40);     //  3
x+=1;                           //  4

It seems like : 2 and 4 are executed before 1 (x becomes 11). Then only 2 is executed before 3 (x becomes 21).

question 1 : Why 2 and 4 are executed before 1?

question 2 : Considering the answer to question 1, why 4 isn't also executed a second time before 3?

This question is very popular :

how does paint() work

why is my code executing paintComponent(Graphics page) twice?

Why does the paint method run twice?

paint() in java applet is called twice for no reason

http://www.java-forums.org/awt-swing/58131-help-yet-another-paint-called-twice-thread.html

At its first run, it prints x=0 x=10 , as I've expected. (x becomes 11 at the end of this first run). Then paint() method runs again (this time starting with ax value of 11) and it prints x=11 x=21, which is the final view of the applet window.

Proof : you can add some code to pause the program for a few seconds after x+=1 , and when you run the program, first you'll see x=0 x=10, then it will change to x=11 x=21 .

What to take home : Write your paint() method as if it will run x times (you can't know x beforehand). So don't make your calculations in it.

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