Basically, I have this game where once guesses the correct answer it starts a new game with a new word. I want to display Correct! but after three seconds, change it to a empty string. How do I do that?
My attempt:
if (anagram.isCorrect(userInput.getText()))
{
anagram = new Anagram();
answer.setText("CORRECT!");
word.setText(anagram.getRandomScrambledWord());
this.repaint();
try
{
Thread.currentThread().sleep(3000);
}
catch (Exception e)
{
}
answer.setText("");
} else
{
answer.setForeground(Color.pink);
answer.setText("INCORRECT!");
}
Edit:
My solution:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
if (anagram.isCorrect(userInput.getText()))
{
answer.setText("CORRECT!");
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
anagram = new Anagram();
word.setText(anagram.getRandomScrambledWord());
answer.setText("");
userInput.setText("");
}
};
Timer timer = new Timer(3000, taskPerformer);
timer.setRepeats(false);
timer.start();
} else
{
answer.setForeground(Color.pink);
answer.setText("INCORRECT!");
}
}
I am not sure, but I hope that I am following MadProgrammer's advice and not blocking the event itself, but the new thread. I will look up Java Timer also.
Swing is an event driven environment. While you block the Event Dispatching Thread, no new events can be processed.
You should never block the EDT with any time consuming process (such as I/O, loops or Thread#sleep for example).
You might like to have a read through The Event Dispatch Thread for more information.
Instead, you should use a javax.swing.Timer. It will trigger a ActionListener after a given delay.
The benefit of which is that the actionPerformed method is executed with the context of the Event Dispatching Thread.
Check out this or this or this or this for an examples
it works after 3 seconds..
ActionListener taskPerformer = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
statusbar.setText("Status");
}
};
Timer timer = new Timer(3000, taskPerformer);
timer.setRepeats(false);
timer.start();
if these piece of code is in the event handlers, then you are holding up the UI thread, and it is not going to work as UI update will only happens after you finished your work in the event handlers.
You should create another thread do the work of "sleep 3 second, and change the text field, and trigger repaint". Using Timer or similar utilities is the easiest way to achieve what I am describing.
Related
boolean flag = true;
public void run(){
// some code
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
flag = false;
// Some code
}
});
while(flag){}
}
I am using while loop till the actionListener is invoked which I think is silly perhaps. Please let me know if this can be done in more efficient way.
You dont need a Thread for the Listener itself, the Java UI Thread calls your Listener for you.
However if you want your response to the event non-blocking do the following:
// no need for a second thread here
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If you dont want to block the UI Thread make a new Thread here
new Thread(YOUR_RUNNABLE).start();
}
}
Related Question
I have an array of strings which I'm trying to display (one by one) as a slideshow in a Java Swing component. I am also trying to add a delay time between the iterations.
I attempted to do this by using a JTextArea, with an action listener added to it. Here is the code I have right now:
private class myActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// A BUNCH OF TEXT PROCESSING
//NOTE: myInfo.getContents() returns an ArrayList<myType>.
Iterator<myType> iterator = myInfo.getContents().iterator();
int i = 0;
while (iterator.hasNext()) {
myTextArea.setText(iterator.next().toString());
// to add time betweeen iterations i wanted to use the thread
// delay method.
}
}
}
My code is not working because JTextArea doesn't have an action listener.
UPDATE
NOTE: Many replies stated that I should use an ActionListener for the JTextArea; However, Eclipse is not showing me that JTextArea has a method called addActionListener.
I'm kind of stuck here, which Java Swing component do you think would be the most suitable in this scenario?
The text in my array may be long, so a one lined label would not be a good choice.
What other alternatives or approaches do I have?
Thank you very much, any help and suggestions are appreciated.
This is basic example is based on the suggestion posted by #Robin
public class TestDisplayString {
public static void main(String[] args) {
new TestDisplayString();
}
public TestDisplayString() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
private List<String> content;
private Iterator<String> iterator;
public TestPane() {
readText();
setLayout(new BorderLayout());
textArea = new JTextArea(10, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
add(new JScrollPane(textArea));
iterator = content.iterator();
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (iterator.hasNext()) {
textArea.setText(iterator.next());
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
protected void readText() {
content = new ArrayList<>(25);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Text.txt")));
String text = null;
while ((text = reader.readLine()) != null) {
if (text.trim().length() > 0) {
content.add(text);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
}
}
This is the contents of the "Text.txt" file.
How to Use Swing Timers
A Swing timer (an instance of javax.swing.Timer) fires one or more
action events after a specified delay. Don't confuse Swing timers with
the general-purpose timer facility that was added to the java.util
package in release 1.3. This page describes only Swing timers.
In general, we recommend using Swing timers rather than
general-purpose timers for GUI-related tasks because Swing timers all
share the same, pre-existing timer thread and the GUI-related task
automatically executes on the event-dispatch thread. However, you
might use a general-purpose timer if you don't plan on touching the
GUI from the timer, or need to perform lengthy processing.
You can use Swing timers in two ways:
To perform a task once, after a delay.
For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
To perform a task repeatedly.
For example, you might perform animation or update a component that displays progress toward a goal.
Swing timers are very easy to use. When you create the timer, you
specify an action listener to be notified when the timer "goes off".
The actionPerformed method in this listener should contain the code
for whatever task you need to be performed. When you create the timer,
you also specify the number of milliseconds between timer firings. If
you want the timer to go off only once, you can invoke
setRepeats(false) on the timer. To start the timer, call its start
method. To suspend it, call stop.
Note that the Swing timer's task is performed in the event dispatch
thread. This means that the task can safely manipulate components, but
it also means that the task should execute quickly. If the task might
take a while to execute, then consider using a SwingWorker instead of
or in addition to the timer. See Concurrency in Swing for instructions
about using the SwingWorker class and information on using Swing
components in multi-threaded programs.
Let's look at an example of using a timer to periodically update a
component. The TumbleItem applet uses a timer to update its display at
regular intervals. (To see this applet running, go to How to Make
Applets. This applet begins by creating and starting a timer:
timer = new Timer(speed, this); timer.setInitialDelay(pause);
timer.start();
The speed and pause variables represent applet parameters; as
configured on the other page, these are 100 and 1900 respectively, so
that the first timer event will occur in approximately 1.9 seconds,
and recur every 0.1 seconds. By specifying this as the second argument
to the Timer constructor, TumbleItem specifies that it is the action
listener for timer events.
After starting the timer, TumbleItem begins loading a series of images
in a background thread. Meanwhile, the timer events begin to occur,
causing the actionPerformed method to execute:
public void actionPerformed(ActionEvent e) {
//If still loading, can't animate.
if (!worker.isDone()) {
return;
}
loopslot++;
if (loopslot >= nimgs) {
loopslot = 0;
off += offset;
if (off < 0) {
off = width - maxWidth;
} else if (off + maxWidth > width) {
off = 0;
}
}
animator.repaint();
if (loopslot == nimgs - 1) {
timer.restart();
} }
Until the images are loaded, worker.isDone returns false, so timer
events are effectively ignored. The first part of the event handling
code simply sets values that are employed in the animation control's
paintComponent method: loopslot (the index of the next graphic in the
animation) and off (the horizontal offset of the next graphic).
Eventually, loopslot will reach the end of the image array and start
over. When this happens, the code at the end of actionPerformed
restarts the timer. Doing this causes a short delay before the
animation sequence begins again.
Use your ActionListener in combination with a javax.Swing.Timer. The ActionListener assigned to the Timer will be called on regular intervals with the specified delay.
See the timer tutorial for more information
I have an array of strings which I'm trying to display (one by one) as a slideshow in a Java Swing component. I am also trying to add a delay time between the iterations.
I attempted to do this by using a JTextArea, with an action listener added to it. Here is the code I have right now:
private class myActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// A BUNCH OF TEXT PROCESSING
//NOTE: myInfo.getContents() returns an ArrayList<myType>.
Iterator<myType> iterator = myInfo.getContents().iterator();
int i = 0;
while (iterator.hasNext()) {
myTextArea.setText(iterator.next().toString());
// to add time betweeen iterations i wanted to use the thread
// delay method.
}
}
}
My code is not working because JTextArea doesn't have an action listener.
UPDATE
NOTE: Many replies stated that I should use an ActionListener for the JTextArea; However, Eclipse is not showing me that JTextArea has a method called addActionListener.
I'm kind of stuck here, which Java Swing component do you think would be the most suitable in this scenario?
The text in my array may be long, so a one lined label would not be a good choice.
What other alternatives or approaches do I have?
Thank you very much, any help and suggestions are appreciated.
This is basic example is based on the suggestion posted by #Robin
public class TestDisplayString {
public static void main(String[] args) {
new TestDisplayString();
}
public TestDisplayString() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
private List<String> content;
private Iterator<String> iterator;
public TestPane() {
readText();
setLayout(new BorderLayout());
textArea = new JTextArea(10, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
add(new JScrollPane(textArea));
iterator = content.iterator();
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (iterator.hasNext()) {
textArea.setText(iterator.next());
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
protected void readText() {
content = new ArrayList<>(25);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Text.txt")));
String text = null;
while ((text = reader.readLine()) != null) {
if (text.trim().length() > 0) {
content.add(text);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
}
}
This is the contents of the "Text.txt" file.
How to Use Swing Timers
A Swing timer (an instance of javax.swing.Timer) fires one or more
action events after a specified delay. Don't confuse Swing timers with
the general-purpose timer facility that was added to the java.util
package in release 1.3. This page describes only Swing timers.
In general, we recommend using Swing timers rather than
general-purpose timers for GUI-related tasks because Swing timers all
share the same, pre-existing timer thread and the GUI-related task
automatically executes on the event-dispatch thread. However, you
might use a general-purpose timer if you don't plan on touching the
GUI from the timer, or need to perform lengthy processing.
You can use Swing timers in two ways:
To perform a task once, after a delay.
For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
To perform a task repeatedly.
For example, you might perform animation or update a component that displays progress toward a goal.
Swing timers are very easy to use. When you create the timer, you
specify an action listener to be notified when the timer "goes off".
The actionPerformed method in this listener should contain the code
for whatever task you need to be performed. When you create the timer,
you also specify the number of milliseconds between timer firings. If
you want the timer to go off only once, you can invoke
setRepeats(false) on the timer. To start the timer, call its start
method. To suspend it, call stop.
Note that the Swing timer's task is performed in the event dispatch
thread. This means that the task can safely manipulate components, but
it also means that the task should execute quickly. If the task might
take a while to execute, then consider using a SwingWorker instead of
or in addition to the timer. See Concurrency in Swing for instructions
about using the SwingWorker class and information on using Swing
components in multi-threaded programs.
Let's look at an example of using a timer to periodically update a
component. The TumbleItem applet uses a timer to update its display at
regular intervals. (To see this applet running, go to How to Make
Applets. This applet begins by creating and starting a timer:
timer = new Timer(speed, this); timer.setInitialDelay(pause);
timer.start();
The speed and pause variables represent applet parameters; as
configured on the other page, these are 100 and 1900 respectively, so
that the first timer event will occur in approximately 1.9 seconds,
and recur every 0.1 seconds. By specifying this as the second argument
to the Timer constructor, TumbleItem specifies that it is the action
listener for timer events.
After starting the timer, TumbleItem begins loading a series of images
in a background thread. Meanwhile, the timer events begin to occur,
causing the actionPerformed method to execute:
public void actionPerformed(ActionEvent e) {
//If still loading, can't animate.
if (!worker.isDone()) {
return;
}
loopslot++;
if (loopslot >= nimgs) {
loopslot = 0;
off += offset;
if (off < 0) {
off = width - maxWidth;
} else if (off + maxWidth > width) {
off = 0;
}
}
animator.repaint();
if (loopslot == nimgs - 1) {
timer.restart();
} }
Until the images are loaded, worker.isDone returns false, so timer
events are effectively ignored. The first part of the event handling
code simply sets values that are employed in the animation control's
paintComponent method: loopslot (the index of the next graphic in the
animation) and off (the horizontal offset of the next graphic).
Eventually, loopslot will reach the end of the image array and start
over. When this happens, the code at the end of actionPerformed
restarts the timer. Doing this causes a short delay before the
animation sequence begins again.
Use your ActionListener in combination with a javax.Swing.Timer. The ActionListener assigned to the Timer will be called on regular intervals with the specified delay.
See the timer tutorial for more information
I have a save button in a JFrame ;on clicking save the 'save' text sets to 'saving....'; I need to set that text as 'saved' after a delay of 10 seconds.How is it possible in java?
Please help...
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
This is what i did...but this wont shows as 'saving' during that delayed time.
If you want to provide the user with visual feedback that something is going on (and maybe give some hint about the progress) then go for JProgressBar and SwingWorker (more details).
If on the other hand you want to have a situation, when user clicks the button and the task is supposed to run in the background (while the user does other things), then I would use the following approach:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false); // change text if you want
new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
// Do the calculations
// Wait if you want
Thread.sleep(1000);
// Dont touch the UI
return null;
}
#Override
protected void done() {
try {
get();
} catch (Exception ignore) {
} finally {
button.setEnabled(true); // restore the text if needed
}
}
}.execute();
}
});
Finally, the initial solution that was using the Swing specific timer:
final JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Take somehow care of multiple clicks
button.setText("Saving...");
final Timer t = new Timer(10000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
button.setText("Saved");
}
});
t.setRepeats(false);
t.start();
}
});
This question & first 3 answers are heading down the wrong track.
Use a JProgressBar to show something is happening. Set it to indeterminate if the length of the task is not known, but presumably you know how much needs to be saved and how much is currently saved.
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Use a SwingWorker for long running tasks. See Concurrency in Swing for more details.
The best is to use a timer and its method execute with a delay : http://developer.apple.com/library/mac/documentation/java/reference/javase6_api/api/java/util/Timer.html#schedule(java.util.TimerTask, long). Use a timertask to wrap your runnable and that's it.
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
logger.finest("Reading SMTP Info.");
}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(false);
timer.start();
According to the documentation this timer should fire once but it never fires.
I need it to fire once.
This simple program works for me:
import java.awt.event.*;
import javax.swing.*;
public class Test {
public static void main(String [] args) throws Exception{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
System.out.println("Reading SMTP Info.");
}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(false);
timer.start();
Thread.sleep(5000);
}
}
This Program will work fine...
setRepeats(boolean flag) function used to set call the function(actionPerformed) repeatedly or only one time if
timer.setRepeats(false) == timer calls the actionperformed method for only one time
timer.setRepeats(true) == timer calls the actionPerformed method repeatedly based on specified time
Swing Timer Work
do the task one time
do the task repeated time
steps to create swing timer:
create the actionlistener
create the timer constructor then pass time and actionlistener in that
implement the actionPerformed() function in which do your task
use timer.start() for start the task between the time specified in timer constructor, use timer.stop() for stop the task
Example:
ActionListener al=new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//do your task
if(work done)
timer.stop();//stop the task after do the work
}
};
Timer timer=new Timer(1000,al);//create the timer which calls the actionperformed method for every 1000 millisecond(1 second=1000 millisecond)
timer.start();//start the task
Your task likely only needs to report results on the event thread (EDT) but do the actual work in a background thread at some periodic rate.
ScheduledExecutorService is EXACTLY what you want. Just remember to update the state of your UI on the EDT via SwingUtility.invokeLater(...)
I'm guessing from the log statement that you're doing some sort of SMTP operation. I think I'm right in saying the java.swing.Timer is intended for UI related timed operations, hence why it needs and EDT running. For more general operations you should use java.util.Timer.
This article is linked from the JavaDocs - http://java.sun.com/products/jfc/tsc/articles/timer/