简体   繁体   中英

Smooth movement of JButton on an action

How can I smoothly move the JButton if action performed (eg the button is pushed). Here's my example but it doesnt work propely:

   public void actionPerformed(ActionEvent event) {
   for(int i = 0; i<50; i++){
          ww.button.setLocation(ww.button.getLocation().x+1, ww.button.getLocation().y);//ww is a JFrame child
      try {
        Thread.sleep(20);

    } catch (InterruptedException e) {
        e.printStackTrace();
    }

   }

After action performed I get a delay in 20*50 ms and button location set in previous loc + 50px, without intermediate locations.

Always try to avoid Thread while working with Swing. In your code it will make main EDT thread to sleep and that's why you are not able to view intermediate locations. Try this with using Swing Timer and you will get it working as intended. Take a look here: How to Use Swing Timers and also try using Swing workers .

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