Jure Bajc
Jure Bajc

Reputation: 3

Java Swing Timer how to use it

I basecally want it to press "Space" to start the timer then stop it after a certain Y cordinate point and then start again when "Space" key is pressed if that makes sence. curently it isnt really working its just stopping completely and not "Purging" so im kinda lost rn. if any of you have a idea about this please share!!

iv been thinking and i probably need a String for my timer which i never done before so any help or a link to an article would be helpful

here's what iv done so far.

if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
    long počasi=10;
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            y1 = y1 - 1;
            jButton2.setLocation(x1, y1);
            if (y1 < 0) {
                timer.cancel();
                jButton2.setLocation(x, y);
                timer.purge();
            }
        }
    }, new Date(), počasi);
}

Upvotes: 0

Views: 77

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

First start by having a look at How to use Swing Timers and Concurrency in Swing for details about how to use Swing Timer and why you should.

Next, in your class, create a timer property...

private Timer timer;

Then in your constructor, create an instance of the Timer...

timer = new Timer(5, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        y1 = y1 - 1;
        if (y1 < 0) {
            y1 = 0;
            timer.stop();
        }
        jButton2.setLocation(x1, y1);
    }
});

Then, when you need to, start the timer...

if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
        long počasi=10;
        if (!timer.isRunning()) {
            timer.start();
        }
}

Next, go read How to Use Key Bindings which will solve all the issues with KeyListener, especially if you have other controls which can obtain keyboard focus

Also, remember, component animation is difficult. If your container has a layout manager, you will be fighting it

Upvotes: 1

Related Questions