Bhavik Kama Bhavik Kama - 1 year ago 60
Java Question

How can I keep executing work while a button is pressed?

I want to keep executing work while a button is pressed, using Java. When the button is released, the work should stop. Something like this:

for(int i=0;i<100;i++)
print "count"

How might I achieve this?

Answer Source

One way:

  • Add a ChangeListener to the JButton's ButtonModel
  • In this listener check the model's isPressed() method and turn on or off a Swing Timer depending on its state.
  • If you want a background process, then you can execute or cancel a SwingWorker in the same way.

An example of the former:

import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ButtonPressedEg {
   public static void main(String[] args) {
      int timerDelay = 100;
      final Timer timer = new Timer(timerDelay , new ActionListener() {

         public void actionPerformed(ActionEvent e) {
            System.out.println("Button Pressed!");

      JButton button = new JButton("Press Me!");
      final ButtonModel bModel = button.getModel();
      bModel.addChangeListener(new ChangeListener() {

         public void stateChanged(ChangeEvent cEvt) {
            if (bModel.isPressed() && !timer.isRunning()) {
            } else if (!bModel.isPressed() && timer.isRunning()) {

      JPanel panel = new JPanel();

      JOptionPane.showMessageDialog(null, panel);