0

I'm using java application. I have a button. When button clicked, fires pressed event. I want in pressed event run a function until boolean myBool be true. I use myBool = false in released event. But when I do it, it do pressed function event always and system crashed. How can I do?

Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73

1 Answers1

0

thanks to d_ominic and Hovercraft Full Of Eels

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

   }
}
Community
  • 1
  • 1
Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73