jeudi 28 juin 2018

How to start java swing timer?

Right now, the object moves a certain increment each time I manually click a button, but its actually suppose to move on its own across the screen on its own once a button is clicked. I tried calling timer.start(); various times in my code. As well as, setting up an 'if' statement in the actionPerformed method that checks for a button being pressed and then calls timer.start() as a result. But, it didn't get the object to move on its own.

Can anyone lead me in the right direction? Am I not writing the code right? Or is does this problem have something to do with java swing timer.

PS. I am new to java,

This is what I have imported in the beginning :

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;

And this is part of my code :

 public void actionPerformed(ActionEvent e){

    if (e.getSource() == rightBtn) {    
        objXpos += objMoveIncrement;
        direction = "right";
        direction.equals("Right");

    }
    if (e.getSource() == leftBtn) {
        direction = "left";
        direction.equals("Left");
        objXpos -= objMoveIncrement;
    }

    repaint();

} } **edit the timer is suppose to start once a button is clicked, and the timer is what allows the object to move across the screen




Aucun commentaire:

Enregistrer un commentaire