in main if the following code is used
Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
}
});
timer.start();
Thread.sleep(3000);
boo will be printed every 200 milliseconds as expected.
While
Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
}
});
timer.start();
nothing will be output!
Presumably the code you're showing is in main(). When main() returns, the program exits before the timer thread has a chance to get going. The sleep gives the JVM enough time to create the other thread, which then allows the JVM to keep running.
Could it be that the Thread.sleep is on the main thread and that the reason nothing is printed in the second case is that the main thread goes away and the program exits?
Is that the complete program (is that the only code in your main method)? If yes, then in the second case the program ends before the timer goes off, so it won't print anything, because the program is finished almost immediately.
1) this code wokrs and in all cases is correct
Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("boo");
}
});
timer.start();
you have to check if javax.swing.Timer#setRepeats() have true value (default value), if isn't changed, otherwise you have a code that block Event Dispatch Thread, thenafter Swing's Timer too,
2) don't use Thread.sleep(int) during EDT, and untill Sleep ended caused this code block for EDT,
Related
On clicking an image I want another image to be displayed pause for one second and the original image to be restored and displayed againdisplayed again When I try to do it it action handler such as code given below it sets the image after sleep .I want the image to be displayed pause and the original to be displayed again how can I achieve that
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
try { //sleep 1 seconds
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg")); }
Swing is single threaded, you should never perform long running or blocking operations within the context of the Event Dispatching Thread
Swing is NOT thread safe, this means you should never update the UI (and anything the UI needs) outside of the context of the EDT
The simplest solution to your problem is to use a Swing Timer
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));
}
});
timer.setRepeats(false);
timer.start();
}
See Concurrency in Swing and How to use Swing Timers for more details
You should never invoke Thread.sleep() inside Event Dispatch Thread
because Thread.sleep() will block Event Dispatch Thread and your UI will be Freeze , instead you could use a Timer to achieve your goal
Refer below code,
jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\O.png"));
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jButton16.setIcon(new javax.swing.ImageIcon("C:\\Users\\x\\Documents\\118px-AMIGO.jpg"));
}
});
timer.setRepeats(false);
timer.start();
I have a while loop that is supposed to update the program data and the GUI, but the GUI part freezes until the while loop is done executing.
Here is my code:
while(game.getCompTotal() < 17) {
try {
Thread.sleep(2500);
} catch (Exception ex){
ex.printStackTrace();
}
game.compHit(); // Program data update
updateCardPanels(); // GUI update -- Does not update until the while loop finishes.
if(game.checkCompBust()){
if(JOptionPane.showConfirmDialog(this, "Dealer Busted. Play again?") == JOptionPane.YES_OPTION){
init(); // Reset
}
}
}
I have tried using SwingUtilities.invokeLater() and a Swing Timer but I do not really get how SwingUtilities.invokeLater() works or how to use a Swing Timer on the EDT. My question is how can I have the GUI update at the same time as the program data in the while loop?
Here is my attempted invokeLater() code:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Timer t = new Timer(100, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
updateCardPanels();
}
});
t.setInitialDelay(0);
t.start();
}
});
Looks like your while loop is on EDT and thats why it freezes GUI while it is executing. Never call Thread.sleep on EDT.
All SwingUtilities.invokeLater does is puts the Runnable on a queue so that EDT would run it at some point in time. The SwingUtilities.invokeLater should be run from a non EDT thread. Starting Swing Timer with SwingUtilities.invokeLater is not required. You can start it directly from EDT.
Swing timer uses a separate thread that runs and periodically calls specified ActionListener on EDT thread.
You can replace the while loop with swing timer (lets say with 1sec interval) and check game.getCompTotal() < 17 condition inside its actionPerformed call.
Soo created a timer using extending timertask.
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
timer.purge();
class MyTimeTask extends TimerTask
{
public void run(){
genReelNumbers();
laa++;
if(laa==50){
timer.cancel();
timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);}}}
timer.purge();
timer.schedule(new MyTimeTask(), 0, 50);}});
But im getting a error with the timer already canceled! As you can see i already tried to use the purge(), soo it cancels the "canceled" timers (dont know if that does make any sence). I want to use this timer each time that i press on the label! Any ideas?
First and foremost, this looks to be a Swing application, and if so, you shouldn't be using java.util.Timer and java.util.TimerTask since Swing is single-threaded, and the two classes above create a new thread or threads to achieve their actions, meaning that important code that should be called on the Swing event thread will not be called on this thread. This this risks causing pernicious intermittent and hard to debug threading exceptions to be thrown. Instead use a javax.swing.Timer. Then to stop this timer, simply call stop() on it, and to restart it, simply call start() on it. For more on this, please read: How To Use Swing Timers.
For example, I'm not 100% sure what you're code is supposed to be doing, but it could look something like:
// warning: code not compile- nor run-tested
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
// assuming a javax.swing.Timer field named timer
if (timer != null && timer.isRunning()) {
// if the timer is not null and it's running, stop it:
timer.stop();
}
// TIMER_DELAY is an int constant that specifies the delay between "ticks"
timer = new Timer(TIMER_DELAY, new ActionListener() {
#Override // this method will be called repeatedly, every TIMER_DELAY msecs
public void actionPerformed(ActionEvent e) {
genReelNumbers();
laa++;
if(laa==50){
timer.stop();
// timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);
}
}
});
timer.start();
}
});
after canceling the timer you have no other choice than creating a new object....
I followed the #Hovercraft advice and changed to javax.swing.Timer
It turned out like this:
//The variable "taxa" is the amount of times that i want it to do the task
javax.swing.Timer time1 = new javax.swing.Timer(taxa, new ActionListener() {
public void actionPerformed(ActionEvent e) {
genReelNumbers();
}
});
//starts the timer
time1.start();
//New timertask
TimerTask tt = new TimerTask() {
#Override
public void run() {
//stops the timer
time1.stop();
label_2.setVisible(false);
label_1.setVisible(true);
verificarodas();
}
};
Timer time = new Timer(true);
// the 2000 is how long i want to do the task's
//if i changed to 3000 it would take 3 seconds (remember it has to be a value on miliseconds) to do the 15 times, and soo on
time.schedule(tt, 2000);
I need to write a program that uses a swing countdown timer to do something (in this case, print out a String in the console). It gets the needed delay info from a spinner and executes the code when I hit the Start button. However, when I enter a value in the spinner, it just waits for twice that many seconds and finishes the run without printing out anything.
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
int x = (int) Spinner1.getValue() * 1000;
Timer TIMER = new Timer(x, new MyActionListener());
TIMER.start();
try {
Thread.sleep(x * 2);
} catch (InterruptedException e) {
}
TIMER.stop();
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Something");
}
}
Any help would be greatly appreciated!
The problem is that you are locking out yourself.
With
Thread.sleep(x * 2);
you are blocking the EventDispatchThread that would run your ActionListener. Still the timer internally keeps a flag that the timeout occured and that it should run your ActionListener at the next possible time.
But
TIMER.stop();
is resetting the TIMER, so that the notification is lost.
I am trying to do the following: click a button, button disappears for 2 seconds, text appears for 2 seconds and after those 2 seconds the visibility is reversed. So far I have done this:
btnScan.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
txtScanning.setVisible(true);
btnScan.setVisible(false);
try {
Thread.sleep(2000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
btnScan.setVisible(true);
}
});
and the result is that as soon as I click the btnScan, the whole program freezes for 2 seconds before doing anything. How do I add the delay at the correct order?
You should not call sleep method in your code that dispatches the event. All the work related UI is handled by EDT(Event Dispatch Thread) and a sleep method will cause it to freeze and hence your Swing application will freeze.
To overcome it you should use a Timer. Run the timer and execute the UI manipulation using SwingUtilities.invokeLater so that it is handled by EDT.
import java.util.Timer;
// make it a member variable
Timer timer = new Timer();
........
public void actionPerformed(java.awt.event.ActionEvent evt) {
button.setVisible(false);
timer.schedule(new TimerTask() {
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
button.setVisible(true);
}
});
}
}, 2000);
}
Currently in your code, you are causing the EDT (event dispatcher thread) to pause with the invocation of Thread.sleep
Performing any long running tasks in the EDT will cause your UI to freeze.
To achieve what you desire, use a SwingWorker thread to perform your actions
This might help: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
Swing is a single threaded environment, anything that blocks this thread will prevent it from processing new events, including repaint requests.
Swing is also not thread safe, meaning img you should never create or update the UI from outside the context of the EDT.
In this case you can use a Swing Timer to trigger a callback to occur at some time in the future which (the notification) will be executed within the context of the EDT, making it safe to update the UI with
Take a look at Concurrency in Swing and How to us Swing Timers for more details
Making use of Swing timer, you can do something like this:
btnScan.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtScanning.setVisible(true);
btnScan.setVisible(false);
Timer timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent acv) {
btnScan.setVisible(true);
txtScanning.setVisible(false);
}
});
// setRepeats(false) to make the timer stop after sending the first event
timer.setRepeats(false);
timer.start();
}
});