简体   繁体   English

Java计时器可加快重绘速度

[英]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. 我目前正在使用JPanel计时器来做一些基本的图形,但是我不知道为什么计时器会按指数增长。

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. 您将在paintComponent()方法中创建一个计时器,每次重新绘制组件时都会生成一个新计时器。

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 ,而前一个也将以此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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