i can't see circle moving

后端 未结 2 650
忘了有多久
忘了有多久 2021-01-29 05:26

While using Swing in java, I am trying to move a circle slowly from a starting position to an end position when clicking a button. However, I can\'t see the circle moving. It ju

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 05:28

    As Andrew Thompson said, calling Thread.sleep() without defining a second thread freezes everything, so the solution is to define and run another thread like so:

    class Bute implements ActionListener, Runnable {
        //let class implement Runnable interface
        Thread t;   // define 2nd thread
    
        public void actionPerformed(ActionEvent e) {
    
            t = new Thread(this);   //start a new thread
            t.start();
        }
    
        @Override               //override our thread's run() method to do what we want 
        public void run() {     //this is after some java-internal init stuff called by start()
            //b.setEnabled(false);
            for (int i = 0; i < 150; i++) {
                x++;
                y++;
                m.repaint();
                try {
                    Thread.sleep(50);   //let the 2nd thread sleep
                } catch (InterruptedException iEx) {
                    iEx.printStackTrace();  
                }
            }
            //b.setEnabled(true);
        }
    
    }
    

    The only problem with this solution is that pressing the button multiple times will speed up the circle, but this can be fixed by making the button unclickable during the animation via b.setEnabled(true/false). Not the best solution but it works.

提交回复
热议问题