In the Netbeans IDE, I wrote a program that creates a JButton in a JFrame. The JButton is visible, and it is clickable, but when the JButton is clicked, sometimes the program will not detect it. The cases where this happens is always when I run it from the .jar file Netbeans compiles for you automatically. My code that waits for the JButton to be clicked is as follows:
while(!(btn.getModel().isPressed())){ //btn is the JButton here
}
This works in the Netbeans, when I run it inside the IDE, but it never detects when the JButton is clicked when the program is run with the .jar file. One thing that I did try is to add a delay in the loop. At first I thought that the loop was looping too fast too detect a single click, so I added a delay of 1 millisecond in between:
while(!(btn.getModel().isPressed())){
try{
Thread.sleep(1);
}catch(InterruptedException e){
'//Exception handling
}
}
This also works in the IDE, but it still does not work in the .jar file. Is there a problem with btn.getModel().isPressed()
? If there is a problem, what is a good alternative to btn.getModel().isPressed()
?
You might want to try using an ActionListener.
To add an ActionListener to your button, use this:
btn.addActionListener(new ActionListener(){ });
Now that you've done that, inside of the ActionListener, put this method:
public void actionPerformed(ActionEvent arg0){ }
Now that you've done that, insert the Thread.sleep(1)
into the actionPerformed
method.