简体   繁体   中英

Stop Java swing timer when a specific value reached

Hello I am using the Java Swing timer for a candle to let it burn. 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?

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 )

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:

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.

The logic of your drawing should be in the Swing Timer's ActionListener code. You should change the size of the candle in actionPerformed. if the size is less than a minimum, then in actionPerformed, stop the Timer.

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