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

為{幸葍}努か 提交于 2019-12-07 10:50:07

问题


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:

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

How might I achieve this?


回答1:


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() {

         @Override
         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() {

         @Override
         public void stateChanged(ChangeEvent cEvt) {
            if (bModel.isPressed() && !timer.isRunning()) {
               timer.start();
            } else if (!bModel.isPressed() && timer.isRunning()) {
               timer.stop();
            }
         }
      });

      JPanel panel = new JPanel();
      panel.add(button);


      JOptionPane.showMessageDialog(null, panel);

   }
}



回答2:


You may need to use mousePressed event to start the action

And use mouseReleased event to stop the action (This is neccesary)

For more information refer here




回答3:


I want to keep executing work while a button is pressed

Execute that process in another thread and then your form is not block and you can press the button to cancel or stop the execution.

see :

  • How to stop threads of a Java program?
  • Stop/cancel SwingWorker thread?
  • Control thread through button


来源:https://stackoverflow.com/questions/12225052/how-can-i-keep-executing-work-while-a-button-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!