Wednesday, December 15, 2010

How to implement a 'repeating' Swing JButton ?

Sometimes you want to repeat your JButton action after the button was pressed. This is definitely not rocket-science, but I thought it's nice and small enough to share. Here's the usual code with a one-click action: a 'Next' button that selects the next row in a table.

    nextButton.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent arg0)
      {
        selectNextRow(...);
      }});
For a repeating button, you can replace this code with the code snippet below. Adjust the times appropriately. I wonder why this isn't standard functionality in a Swing JButton(..., startMsec, repeatMsec) ?

    nextButton.addMouseListener( new MouseAdapter() {
      
      Timer repeatTimer;
      
      public void mousePressed(MouseEvent arg0)
      {
        selectNextRow(...); // initial execution
        
        repeatTimer = new Timer(100, new ActionListener() {
          public void actionPerformed(ActionEvent e)
          {
            selectNextRow(...); // execute every 100 msec
          }});
        repeatTimer.setInitialDelay(1000); // start repeating only after 1 second
        repeatTimer.start();
      }
      
      public void mouseReleased(MouseEvent arg0)
      {
        repeatTimer.stop();
      }});

No comments:

Post a Comment