previous the same thread was running in java eclipse luna, but interruptions appeared I changed to Java EE IDE, the same thread which previous ran in luna now is not running in Java EE IDE, here it is
public void clockTime(){
Thread clock=new Thread(){
public void run(){
try {
for(;;){
Calendar cald=new GregorianCalendar();
day=cald.get(Calendar.DAY_OF_MONTH);
month=cald.get(Calendar.MONTH);
year=cald.get(Calendar.YEAR);
seconds=cald.get(Calendar.SECOND);
minutes=cald.get(Calendar.MINUTE);
hours=cald.get(Calendar.HOUR);
lblClock.setText("<html>"+hours+":"+minutes+":"+seconds+"<br>"+day+"/"+month+"/"+year+"</html>");
sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
clock.start();
}
please may any one help me??.
calling the method to constructor I have already done not seen here, but if I remove the thread the method is executed since it displays the time and date as required but not changing due to absence of loop and forever loop.
If this is a Swing application then:
Make sure that you start the application on the Swing event thread, by calling SwingUtilities.invokeLater(Runnable); where your GUI is started up in that Runnable
You're making a key Swing call off of the Swing event thread (EDT) in the code above, namely the lblClock.setText(...) call. This also should be called only on the Swing event thread, in the same way as point above.
Or you could use a SwingWorker and then make the setText call in the publish / process method pair.
Or (and this is what I would do), chuck all that code above and use a Swing Timer. It's much simpler, and you wouldn't have to worry about on/off Swing event since all calls would be on the event thread.
If you go the Swing Timer route, you'd construct pass in its constructor an int equal to the desired delay, here 1000 msecs. The Timer's ActionListener is called repeatedly, and in that you'd get your time values, and then use it to create a String that you pass to your JLabel.
For example, something roughly like:
int timerDelay = 1000;
Timer timer = new Timer(timerDelay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// calculations to get time Strings
String text = ..... // use calculations above
lblClock.setText(text);
}
});
timer.start();
Note that code has not been tested
Related
Related to my previous question: Call repaint from another class in Java?
I'm new to Java and I've had a look at some tutorials on SwingWorker. Yet, I'm unsure how to implement it with the example code I gave in the previous question.
Can anyone please explain how to use SwingWorker with regards to my code snippet and/or point me towards a decent tutorial? I have looked but I'm not sure I understand yet.
Generally, SwingWorker is used to perform long-running tasks in Swing.
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up, so one of the things which were done is to use SwingUtilities.invokeLater and invokeAndWait which keeps the GUI responsive by which prioritizing the other AWT events before running the desired task (in the form of a Runnable).
However, the problem with SwingUtilities is that it didn't allow returning data from the the executed Runnable to the original method. This is what SwingWorker was designed to address.
The Java Tutorial has a section on SwingWorker.
Here's an example where a SwingWorker is used to execute a time-consuming task on a separate thread, and displays a message box a second later with the answer.
First off, a class extending SwingWorker will be made:
class AnswerWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
// Do a time-consuming task.
Thread.sleep(1000);
return 42;
}
protected void done()
{
try
{
JOptionPane.showMessageDialog(f, get());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The return type of the doInBackground and get methods are specified as the first type of the SwingWorker, and the second type is the type used to return for the publish and process methods, which are not used in this example.
Then, in order to invoke the SwingWorker, the execute method is called. In this example, we'll hook an ActionListener to a JButton to execute the AnswerWorker:
JButton b = new JButton("Answer!");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
new AnswerWorker().execute();
}
});
The above button can be added to a JFrame, and clicked on to get a message box a second later. The following can be used to initialize the GUI for a Swing application:
private void makeGUI()
{
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout());
// include: "class AnswerWorker" code here.
// include: "JButton" b code here.
f.getContentPane().add(b);
f.getContentPane().add(new JButton("Nothing"));
f.pack();
f.setVisible(true);
}
Once the application is run, there will be two buttons. One labeled "Answer!" and another "Nothing". When one clicks on the "Answer!" button, nothing will happen at first, but clicking on the "Nothing" button will work and demonstrate that the GUI is responsive.
And, one second later, the result of the AnswerWorker will appear in the message box.
Agree:
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up.
Do not agree:
so one of the things which were done is to use SwingUtilities.invokeLater and invokeAndWait which keeps the GUI responsive..
invokeLater still runs the code on the EDT, and can freeze your UI!! Try this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
At least I, cannot move my mouse once I click the button which triggers the actionPerformed with the above code. Am I missing something?
Currently in my brief time with Java I have made a clicker game and I've been trying to implement a way to add a number to an integer (or the int command) every couple of seconds. but whatever I try just stops the entire program completely such as the
Thread.sleep(15000);
wait(15000);
even if they are in a try and catch it just stops the program and not complete a loop every couple of seconds.
If you have Thread.sleep(xxx); in the current thread, then yes, it will stop the current thread for xxx seconds. Because (most likely) Thread.sleep is in the same thread that is controlling the GUI, it is pausing your code from executing, freezing your application. There are two ways you can fix this:
Create a new thread and place the timer code in there:
SwingUtilities.invokeLater will add your Runnable to the queue of threads that AWT executes.
// Because the code is in a different thread, Thread.sleep(1000) will not pause
// the current thread and the application will continue as normal
Thread thread = new Thread(new Runnable() {
int seconds = 0;
#Override
public void run()
{
while (true) {
// wait one second
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
};
// increment seconds
seconds++;
System.out.println(seconds);
}
}
});
thread.start();
Use an existing timer in the Java API
Look at ScheduledThreadPoolExecutor and its scheduleAtFixedRate method. Here's an example. You could also use a swing timer as mentioned in the comment by Hovercraft Full Of Eels.
To use a Swing timer, you import javax.swing.Timer (not java.util.Timer), create a Timer object with the delay and an action listener listening for when it will fire events, and start it.
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent a)
{
System.out.println("Timer went off!");
}
});
// Repeat every second
timer.start();
Note that this code won't execute on its own; you need to have a GUI running.
Hey i just need a question answered...
How would i make the following code not freeze my whole JFrame?
try {
Thread.sleep(Integer.parseInt(delayField.getText()) * 1000);
System.out.println("Hello!");
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
use a different thread to perform this task. If you do this in the main UI thread then it will freeze.. For example you can do following
new Thread() {
#Override
public void run() {
try {
Thread.sleep(Integer.parseInt(delayField.getText()) * 1000);
System.out.println("Hello!");
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}.start();
UPDATE
AFter wise suggestions of Robin and Marko I am updating the answer with a better solution.
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Hello!");
}
};
javax.swing.Timer t = new javax.swing.Timer(Integer.parseInt(delayField.getText()) * 1000, taskPerformer);
t.setRepeats(false);
t.start();
Whenever you are about to use Thread.sleep in your GUI code, stop yourself and think of Swing Timer, which is the right tool for the job. Schedule the task you need to perform with a delay.
Using another thread for this is not the best advice: it wastes a heavy system resource (a thread) to do absolutely nothing but wait.
This is not the correct way to use threads in java . You should use swingutilities.invokelater
swing utils invoke later
You don't want to execute this on the UI (or event dispatch thread) thread. Rather in a separate thread. Otherwise (as you've seen) you'll block the UI.
It's a good practice to perform time-consuming operations on a separate thread, and make use of SwingUtilities.invokeLater() if those threads need to perform some subsequent UI action (e.g. in the above display "Hello" in the UI)
I'm making a simple game in Java using swing and am having problems with my GUI freezing up sporadically (due to threading issues most probably) after a button press that is supposed to trigger a switch in JPanels.
I posted a related thread here, which has more details about the actual code I'm currently using (although I did update the countdown and get that working fine). From answers to that thread, it seems like usingSwingUtilities.invokeLater() or invokeAndWait() might be what I need to solve the problem, but I'm not sure where in my code it is necessary or exactly how to implement it.
I don't know that much about threading and could use any help (preferably somewhat detailed and with some sample code) that I can get. Let me know if any further details would be useful.
See: Tutorial: Concurrency in Swing
Generally speaking, the Event Dispatch Thread is a single thread, chugging through the event queue, processing one at a time.
SwingUtilities.invokeLater(..)
puts a Runnable on this queue. So it will be processed by the EDT when the EDT finishes everything on the queue before it (This is why sleeping on the queue blocks other events like repainting). It's relatively unusual to call invokeLater(..) from the EDT itself, though there are situations where it is useful (usually as a hack). I don't think I have had a legitimate use for SwingUtilities.invokeAndWait(..) in the last 6 years. Maybe once.
javax.swing.Timer can be configured to fire once or periodically. When it fires, it puts an event on the EDT queue. If you have computationally-intensive processing that need to be done, consider using javax.swing.SwingWorker to do the computation on another thread, and give you back the result in a thread-safe manner (this is also comparatively rare).
A good point to look is the docs. In your case, this explains how SwingUtilities.invokeLater() works and where to use it:
Causes doRun.run() to be executed asynchronously on the AWT event
dispatching thread. This method should be used when an application
thread needs to update the GUI.
So, in your actions that modifies the GUI you must use the invokeLater method to assure that the GUI wont freeze.
Another good resource is the Java tutorials. They cover concurrency in Swing.
I have create a WorkerThread class which take care of Threads and GUI current/main thread . i have put my GUI application in construct() method of WorkerThread when an event fire to start XXXServer then all threads are activate and GUI work smoothlly wihout freeze. have a look.
/**
* Action Event
*
* #see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent ae) {
log.info("actionPerformed begin..." + ae.getActionCommand());
try {
if (ae.getActionCommand().equals(btnStart.getText())) {
final int portNumber = 9990;
try {
WorkerThread workerThread = new WorkerThread(){
public Object construct(){
log.info("Initializing the XXXServer ...");
// initializing the Socket Server
try {
XXXServer xxxServer = new XXXServer(portNumber);
xxxServer.start();
btnStart.setEnabled(false);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("actionPerformed() Start button ERROR IOEXCEPTION..." + e.getMessage());
e.printStackTrace();
}
return null;
}
};workerThread.start();
} catch (Exception e) {
log.info("actionPerformed() Start button ERROR..." + e.getMessage());
e.printStackTrace();
}
} else if (ae.getActionCommand().equals(btnStop.getText())) {
log.info("Exit..." + btnStop.getText());
closeWindow();
}
} catch (Exception e) {
log
.info("Error in ServerGUI actionPerformed==="
+ e.getMessage());
}
}
In order to invoke an action in the existing WorkerThread, one would intuitively send a user defined event using SwingUtilities.invokeLater() to a JFrame's actionPerformed() method as
class TestFrame extends JFrame implements ActionListener
{
...
private class Performer implements Runnable
{
ActionEvent event;
Performer(ActionEvent event)
{
this.event = event;
}
#Override
public void run()
{
actionPerformed(event);
}
}
synchronized protected void invokeLater(ActionEvent event)
{
SwingUtilities.invokeLater(new Performer(event));
}
public void actionPerformed(ActionEvent event)
{
...
}
}
Now, TestFrame.invokeLater() called in any Thread will be processed in TestFrame.actionPerformed() in existing WorkerThread .
Related to my previous question: Call repaint from another class in Java?
I'm new to Java and I've had a look at some tutorials on SwingWorker. Yet, I'm unsure how to implement it with the example code I gave in the previous question.
Can anyone please explain how to use SwingWorker with regards to my code snippet and/or point me towards a decent tutorial? I have looked but I'm not sure I understand yet.
Generally, SwingWorker is used to perform long-running tasks in Swing.
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up, so one of the things which were done is to use SwingUtilities.invokeLater and invokeAndWait which keeps the GUI responsive by which prioritizing the other AWT events before running the desired task (in the form of a Runnable).
However, the problem with SwingUtilities is that it didn't allow returning data from the the executed Runnable to the original method. This is what SwingWorker was designed to address.
The Java Tutorial has a section on SwingWorker.
Here's an example where a SwingWorker is used to execute a time-consuming task on a separate thread, and displays a message box a second later with the answer.
First off, a class extending SwingWorker will be made:
class AnswerWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
// Do a time-consuming task.
Thread.sleep(1000);
return 42;
}
protected void done()
{
try
{
JOptionPane.showMessageDialog(f, get());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The return type of the doInBackground and get methods are specified as the first type of the SwingWorker, and the second type is the type used to return for the publish and process methods, which are not used in this example.
Then, in order to invoke the SwingWorker, the execute method is called. In this example, we'll hook an ActionListener to a JButton to execute the AnswerWorker:
JButton b = new JButton("Answer!");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
new AnswerWorker().execute();
}
});
The above button can be added to a JFrame, and clicked on to get a message box a second later. The following can be used to initialize the GUI for a Swing application:
private void makeGUI()
{
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout());
// include: "class AnswerWorker" code here.
// include: "JButton" b code here.
f.getContentPane().add(b);
f.getContentPane().add(new JButton("Nothing"));
f.pack();
f.setVisible(true);
}
Once the application is run, there will be two buttons. One labeled "Answer!" and another "Nothing". When one clicks on the "Answer!" button, nothing will happen at first, but clicking on the "Nothing" button will work and demonstrate that the GUI is responsive.
And, one second later, the result of the AnswerWorker will appear in the message box.
Agree:
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up.
Do not agree:
so one of the things which were done is to use SwingUtilities.invokeLater and invokeAndWait which keeps the GUI responsive..
invokeLater still runs the code on the EDT, and can freeze your UI!! Try this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
At least I, cannot move my mouse once I click the button which triggers the actionPerformed with the above code. Am I missing something?