简体   繁体   中英

Java timer speeds up with repaint

I'm currently doing some basic graphics with timer in a JPanel , but I cant figure out, why the timer goes up exponentially.

Here's my code:

public class panel extends JPanel implements ActionListener {
    int r = 20;
    Timer forgo;

    public panel(){
        setSize(400,400);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawOval(r, 20, 20, 20);
        forgo = new Timer(1000,this);
        forgo.start();
    }

    public void actionPerformed(ActionEvent e) {
        r+=5;
        repaint();
        System.out.println(r);
    }
}

so as you can see I try to make an oval go to the right edge of the panel, but my console prints out something like:

25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
105
110
115
120
125
130
135
140
145
150
155

after a few seconds, I can't figure out why this is speeding up.

You're creating a timer in the paintComponent() method, which spawns a new timer every time the component is repainted.

The "speeding up" you see is the large quantity of timers you've created taking effect concurrently.

You could try creating the timer only once, which prevents this from occurring.

作为@APerson说,原因是数额巨大的Timers会派生每次你的时间component被粉刷一新,第一次的时候你的组件是被系统调用它增加了1个定时器与时间间隔1000毫秒内存,后1000毫秒Timer会重新粉刷component这将导致在内存中添加一个新的Timer ,第二个Timer将在1000毫秒后添加新的Timer ,这时它将repaintcomponent ,而前一个也将以此类推。

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