0
package getcm;

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class test {
    public static void main( String[] args ) {
        tpanel panel = new tpanel();
        JFrame app = new JFrame();
        app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        app.add(panel);
        app.setSize(250, 250);
        app.setVisible(true);
    }
}
class tpanel extends JPanel {
    int st = 0;
    public void paintComponent(Graphics g) {
        for (int h = 0; h < 2; h++) {
            System.out.println(st);
            st += 1;
        }
    }
}

I think this result should be 0, 1 but in Eclipse, the data that printed is 0, 1 ,2 ,3.

I have a reason that variable st can not produce inside the fuction paintComponent, and I have to get result 0, 1. (getting paintComponent only one time)

Please help me to get result 0, 1.

I have no idea about why this code print 0, 1 ,2 ,3 not 0, 1.

fnclovers
  • 119
  • 9

2 Answers2

0

Because paintComponent get called multiple times, everytime the panel get painted it'll print a couple of number 0,1 for the frist paint and 2,3 for the second


If you edit the code like this it will print

class tpanel extends JPanel {
    int st = 0;
    public void paintComponent(Graphics g) {
        for (int h = 0; h < 2; h++) {
            System.out.println(st);
            st += 1;
        }
        Systen.out.println("paintComponent completed");
    }
}

Output:

0
1
paintComponent completed
2
3
paintComponent completed
Emax
  • 1,343
  • 2
  • 19
  • 30
  • Yes, Thanks for helping me. But I'm in the situation that I have to use variable (st) in another circumstances and I want to call paintComponent only one time. doen't you have an idea? – fnclovers Aug 22 '17 at 12:08
  • You don't call paintComponent is the swing framwork that call it, you can't do nothing about it, i suggest you to read this https://stackoverflow.com/a/15545309/2508770 – Emax Aug 22 '17 at 12:11
0

It is happening only on frame resize. When resizing the frame, your paintComponent is called again with the old value of variable "st". It is because, for the class "tpanel", "st" is a global variable and until your JPanel remains open, control will not exit from the "tpanel" class.

So simply it is only printing the value of global variable which is called between different function calls of paintComponent.

Hope this will help. :-)

Aman
  • 735
  • 1
  • 6
  • 19