简体   繁体   中英

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

    }

}

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();

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.

I'm not sure if this is the best way, but you could easily redefine a square to have a location. In turn, you could have the timer update the location of your square instance and then call repaint(). This would mean the paint method just draws the background and the same square in its new location instead of creating a new square every time.

Your paint method could then have something like:

g.drawRect(referenceToSquare.getLocation().getX(), referenceToSquare.getLocation().getY(), 100, 100)

You initialize your timer with :

   Timer timer = new Timer(delayInMillis);
   timer.add(new ActionListener());

then in same class have a...

     actionPerformed(ActionEvent e) {
       if(e.getSource() == timer) {
           referenceToSquare.getLocation().getX()++;
       }
       frame.repaint();
     }

http://docs.oracle.com/javase/6/docs/api/java/awt/event/ActionListener.html

I would suggest you use an ExecutorService

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

eg you can do something similar to that

private static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
scheduledThreadPool.scheduleAtFixedRate(new DrawingTask(), 1000, 1000 TimeUnit.MILLISECONDS);

Your drawing task can look similar to below:

public class DrawingTask extends TimerTask {

@Override
public void run() {
// previous co ordinates. This should be static
// sleep for a second
// re draw the old one
// draw the new one
}
}

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