按下按钮时如何继续执行工作?

Use*_*343 4 java onclick jbutton buttonclick

我希望在按下按钮时继续执行工作,使用Java.释放按钮后,工作应该停止.像这样的东西:

Button_is_pressed()
{
    for(int i=0;i<100;i++)
    {
        count=i;
        print "count"
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能实现这个目标?

Hov*_*els 9

单程:

  • 将ChangeListener添加到JButton的ButtonModel
  • 在此侦听器中,检查模型的isPressed()方法,并根据其状态打开或关闭Swing Timer.
  • 如果您想要后台进程,则可以以相同的方式执行或取消SwingWorker.

前者的一个例子:

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);

   }
}
Run Code Online (Sandbox Code Playgroud)

  • +1然后我想到的不那么复杂 (3认同)