how to move jlabel every second?

后端 未结 3 721
耶瑟儿~
耶瑟儿~ 2021-01-16 03:10

i try to move it to the right(x++) every seconds

i try to move it with thread..

  1. how to do it? (and can see it move every second)
  2. there are an
3条回答
  •  逝去的感伤
    2021-01-16 03:50

    • Class names begin with capital letters i.e Help
    • Swing components should be created and modified on Event Dispatch Thread
    • A new Thread is created like this:

      Thread t = new Thread(new Runnable() {
          @Override
          public void run() {
              //work here
          }
      });
      t.start();//start thread
      

    however I'd suggest a Swing Timer as it runs on EDT:

    • How to Use Swing Timers

    EDIT:

    As per your questions I suggest using a Timer the creating thread point was for general knowledge.

    The probelm is the Thread is not run on EDT Thread of your swing GUI where as a Timer does:

     int delay = 1000; //milliseconds
      ActionListener taskPerformer = new ActionListener() {
          int count=0;
          public void actionPerformed(ActionEvent evt) {
               if(count==10) {//we did the task 10 times
                     ((Timer)evt.getSource()).stop();
                }
    
                label.setLocation((label.getLocationOnScreen().x+10), label.getLocationOnScreen().y);
                System.out.println(SwingUtilities.isEventDispatchThread());
               count++;
          }
      };
      new Timer(delay, taskPerformer).start();
    

    Reference:

    • http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

提交回复
热议问题