Javax Swing Timer Help

I am having trouble running javax.swing.Timer after a mouse click. I want to start a timer to perform some animation after the user clicks on the button, but it does not work.

Here are the code snippets:

public class ShowMe extends JPanel{
  private javax.swing.Timer timer;

  public ShowMe(){
    timer = new javax.swing.Timer(20, new MoveListener());
  }    

  // getters and setters here

  private class MoveListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
     // some code here to perform the animation
    }
  }
}

This is the class that contains the button, so when the user clicks on the button, the timer starts to start the animation

public class Test{

 // button declarations go here and registering listeners also here

 public void actionPerformed(ActionEvent e) {
  if(e.getSource() == this.btnConnect){
      ShowMe vis = new ShowMe();
      vis.getTimer().start();
  }
 }
}

I want to start the timer to start the animation, but it does not work.

Need help on how to start a timer after pressing a button.

Thank.

+3
source share
4 answers

You must call the start()timer method to start it.

  public ShowMe(){
    timer = new javax.swing.Timer(20, new MoveListener());
    timer.start();
  }  

:
, start() Test...
/ MouseListener, , .

  private class MoveListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
      System.out.println("MouseListener activated");  // TODO delete this line
     // some code here to perform the animation
    }
  }

( , ), , Ash : , vis, Timer, .
(, ShowMe ...)

+1

, :

  • , , . .

  • , . , , paint(), repaint() , . , (, ), ().

, . avaialbe, :

+1

, , , .

, , ShowMe , , , .

ShowMe, , actionPerformed . ActionListener ShowMe, , actionPerformed , GC.

, ShowMe. , JPanel, , , . , Test ( ), , ShowMe, , .

+1

Timer . , MoveListener.

paintImmediately() ?

repaint(), , repaint() .

+1

Source: https://habr.com/ru/post/1740763/


All Articles