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?
Asked
Active
Viewed 354 times
0

Morteza Malvandi
- 1,656
- 7
- 30
- 73
-
I imagine you'd need some kind of background thread – MadProgrammer Dec 03 '15 at 05:08
-
I can't use thread. I have some restriction. – Morteza Malvandi Dec 03 '15 at 05:09
-
1Does this help? http://stackoverflow.com/questions/12225052/how-can-i-keep-executing-work-while-a-button-is-pressed – domdomcodecode Dec 03 '15 at 05:10
-
can you share your code? may be, you are doing some minor mistake. – mayank agrawal Dec 03 '15 at 05:11
-
Well, frankly, you're screwed. Swing is a single threaded framework, you can't execute another method while the button is pressed, as this would prevent the button from ever been released – MadProgrammer Dec 03 '15 at 05:11
-
If you can't use another `Thread`, then there is no other solution which won't, at some point, use another thread... – MadProgrammer Dec 03 '15 at 05:20
1 Answers
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