Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javax.swing.timer with GUI (Eclipse)

I want to make a code that makes a square move from the left side of the panel to the right side of the panel... I realized that you could simply make a image appear in on block of code and then in the next block of code have the image be overlapped by a exactly the same square just with the same color as the background... To do that I need a timer like code that makes it so that the image appears and then 1 second later it gets over lapped and then the new image appears right beside it

Realizing that sleep.thread doesn't work nice with gui i'm resorting to Javax.Swing.Timer

I just want it to make one box appear beside it for now

However i have no experience with it and need some help getting it to work with my code -Andrew

    {

          g.setColor(Color.GREEN);
          g.fillRect(50, 100, 100, 100); //first box on a red background

                      //Timer goes here

                      g.setColor(Color.RED);
          g.fillRect(50, 100, 100, 100);//overlapps the first box
                      g.setColor(Color.GREEN);
          g.fillRect(50, 110, 100, 100);//sets a new box right beside it

    }

}
like image 960
AAA Avatar asked Apr 13 '26 18:04

AAA


2 Answers

Creating a javax.swing.Timer is quite simple actually. You don't have to worry about the threads yourself, because the scheduling happens automatically in a background thread, but the code of the listener you implement is executed in the GUI thread. Therefore you can work with whatever swing components you need in the listener body.

int interval = 1000; // repeating every 1000 ms
new Timer(interval, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do whatever painting that you want
    }
}).start();
like image 176
Natix Avatar answered Apr 16 '26 08:04

Natix


You initialize it with:

Timer <timernamegoeshere> = new Timer(<delayinmilis>,<actionlistener>);

So every amount of miliseconds you entered into timers constucter an action will performed.

That means that you can simply put your update code into the actionPerformed and have a variable being incremented by the amount of pixels that you move your square by and a boolean, switching from true to false, with true being that it draws it, and false that it sets it to the color of the background.

like image 38
Alex555 Avatar answered Apr 16 '26 09:04

Alex555