简体   繁体   English

达到特定值时停止Java swing计时器

[英]Stop Java swing timer when a specific value reached

Hello I am using the Java Swing timer for a candle to let it burn. 你好我正在使用Java Swing计时器来点燃蜡烛。 everything works well except the end part when the candle is almost burned down to bottom. 除蜡烛几乎烧到底部的末端部分外,一切都很顺利。 the timer should stop when the size is smaller then lets say 15.. Now I made some code and it seems that the if/else statement I made is beeing ignored completely.. Can someone tell me what I do wrong? 当大小较小时计时器应该停止然后让我们说15 ..现在我做了一些代码,似乎我做的if / else语句完全被忽略了..有人能告诉我我做错了吗?

below you can see my code: ( ps the getCandleSize method now brings the length from 500 to 10 > 0 and then i get negative values ) 下面你可以看到我的代码:(ps getCandleSize方法现在带来的长度从500到10> 0然后我得到负值)

package h04SelfBurnCandle;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import h02aKaars.DrawCandle;

public class CandlePanel extends JPanel implements ActionListener {

private boolean aan = true;
private int lengte = 500;
private int x;
private int y;
private int speed = 10;
private final int WACHTTIJD = 100; // wachttijd voor de timer

public CandlePanel() {

    javax.swing.Timer autoburn = new javax.swing.Timer(WACHTTIJD,this);

    autoburn.start();

}

DrawCandle candle = new DrawCandle();

@Override
public void paintComponent(Graphics g) {

    super.paintComponent(g);
    x = 10;
    y = getHeight() - (lengte + 10);

    for(int i=0; i < 5; i++) {

        if(lengte > 15){

        candle.drawCandle(g, x, y, lengte, aan);

        }
        else {

            candle.drawCandleBurned(g, x, y, lengte);

        }

        x = x + 70;

        System.out.println(lengte);

    }

}

public int getCandleSize() {

    do {
        lengte -= speed;
    }
    while(lengte > 15);

    return lengte;
}

@Override
public void actionPerformed(ActionEvent e) {

    getCandleSize();
    //System.out.println(lengte);
    repaint();

}

}

When getCandleSize() gets called but it's going to result in lengte being reduced instantly to 10. What you want is probably more like: getCandleSize()被调用时,它会导致lengte立即减少到10.你想要的更像是:

public int getCandleSize() {
    if(lengte > 15)
        lengte -= speed;
    else
        autoburn.stop();

    return lengte;
}

Note: You will need to change autoburn from a local to a class member. 注意:您需要将autoburn从本地成员更改为类成员。

The logic of your drawing should be in the Swing Timer's ActionListener code. 绘图的逻辑应该在Swing Timer的ActionListener代码中。 You should change the size of the candle in actionPerformed. 你应该在actionPerformed中改变蜡烛的大小。 if the size is less than a minimum, then in actionPerformed, stop the Timer. 如果大小小于最小值,则在actionPerformed中,停止Timer。

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

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