Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to make a program that displays random numbers, bliking one at a time in a JLabel or just in the console. I am making a game, where the player needs to remember the number that was displayed two blinks back in time.
Does anyone know how to make the numbers blink?
I unfortunately don't have any GUI project handy to test it out (I might in a moment as a command line one), but I think that one way to do it is:
(I've removed the HideTask, as it gives some trouble when you want to run it again, and I don't think the task at hand really needs it - just call sleep() :) )
class ShowTask extends TimerTask {
JLabel label;
Random generator = new Random();
//HideTask hTask;
//java.util.Timer timer = new java.util.Timer();
long period = 500; // ms
public Task(JLabel pLabel){
label = pLabel;
//hTask = new HideTask(pLabel);
}
public void run(){
int i = generator.nextInt(100);
setLabel(i);
// if you want it to go SHOW HIDE SHOW HIDE instead of SHOW SHOW SHOW then:
//timer.schedule(hTask, period);
// just wait
Thread.sleep(period);
hideLabel();
}
void setLabel(int i){
...
}
}
/*
class HideTask extends TimerTask {
JLabel label;
public HideTask(JLabel pLabel){
label = pLabel;
}
public void run(){
hideLabel();
}
void hideLabel(){
...
}
}
*/
when you want to start:
ShowTask task = new ShowTask();
long delay = 0; // ms
long period = 1000; // ms
java.util.Timer timer = new java.util.Timer();
timer.scheduleAtFixedRate(task, delay, period);
Note, that it wasn't tested and it is just the first concept I come up with, but maybe you can work forward from it.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I think that this type of question has already been asked but I could not related to any of those questions. I created a stopwatch
and it incremented every 1/100th seconds but that was far from accurate it was not even 60% accurate , I used hanlder.post and handler.post(...., 10).
Use timer. If you using handler.postDelay the problem is the next catch up will be delay few millisecond. It will be a big problem when you running like 1000 second.
Timer timer = new Timer(); //init the timer
Handler handler = new Handler();
int counter = 0; //counter to indicate the total second whenever timer fire
timerTask task = new timerTask();
timer.scheduleAtFixedRate(task,500,1000); //(which task to run,forget the usage try google, looping must be milisecond eg.1000 = 1 second)
private class timerTask extends TimerTask{
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
counter++;
if(counter >= 100){
//do something
}
}
});
}
}
You could take a look with alarm manager as well. But I didn't know wether it is helpful for you or not.
I am trying to simulate a timer. So upon clicking button in the JFrame form, I want the timer to countdown from say 10 to 0. I want it to be exactly 10s. I don't want to find elapsed time of any codes as whatever codes I have found so far give elapsed time. For example using System.nanoTimer().
I tried doing this:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:timer
long startTime = System.nanoTime();
// ... the code being measured ...
long targetTime=startTime+10000;
while(System.nanoTime()<targetTime)
{
JOptionPane.showMessageDialog(this,targetTime-System.nanoTime());
}
JOptionPane.showMessageDialog(this,"time's up");
}
But of course it hardly shows the time left once or twice. Can someone help me with the logic?
10000 nanosec's is 10 miliseconds and that is is 1/100 of one second.
Use:
System.currentTimeMilis
instead
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Alright so i have been trying to run a for loop that runs 60 times. In this for loop i am using Thread.sleep(2000); to ping a server. I want to do this 10 times for this thread but for a separate loop through the for loop. In the mean time i want another 6 threads running doing 10 of their own so this hole process is sped up and completed in around 12 seconds.
for(int i = 0; i < 6; i++) {
//I am starting a new thread here.
}
#Override
public void run() {
//THIS is where i want a each thread to be doing 10 each to speed up the process.
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
I am sorry if this is hard to understand but i tried setting this out in the simplest way possible.
Thanks in advance.
If I get You right, You are not depending on the results, right? Here is a quick handdraft made out of the code:
Thread[] t = new Thread[6];
for(int i = 0; i < 6; i++) {
t[i] = new Thread() {
#Override
public void run() {
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
};
t[i].start();
}
Thread.sleep(longEnough);
This is the cheapest variant for kicking off threads, but beware, it is not professional! You should at least loop over the thread array to call join() on them in order to wait long enough instead of using a time constant.
If You want to do serious threading please consider using Java's ExecutorService (see http://www.vogella.com/tutorials/JavaConcurrency/article.html#threadpools) or ForkJoin of Java 7 (http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)
In your initial for loop, instead of creating Threads, you should be creating Callable instances. Add these into a List, create an Executor, and pass the List to the Executor (FixedThreadPool for example). Then execute the Executor and they'll run in parallel. After all these hints, Ill leave the implementation to you since this looks sneakingly like a homework question.
Im trying to get a timer to work in my current java project that adds 1 to an integer variable every n microseconds (e.g. 500 for 1/2 a second), within an infinite loop, so that it is always running while the program runs.
Heres the code i have currently:
public class Ticker
{
public int time = 0;
long t0, t1;
public void tick(int[] args)
{
for (int i = 2; i < 1; i++)
{
t0 = System.currentTimeMillis();
do
{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < 500);
time = time + 1;
}
}
}
Everyone was so helpful with my last question, hopefully this one is just as easy
Here is an comparable ScheduledExecutorService example which will update the time variable with a 500 millisecond interval:
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(new Runnable(){
private int time = 0;
#Override
public void run(){
time++;
System.out.println("Time: " + time);
}
}, 0, 500, TimeUnit.MILLISECONDS);
This approach is preferred over using Timer.
I think you want
Thread.sleep(500);
At the moment you're consuming CPU cycles waiting for 500ms (you mention microseconds but I believe you want milliseconds). The above puts your current thread to sleep for 500ms and your process won't consume any CPU (or minimal at least - garbage collection will still be running). If you watch the CPU when you run your version you should see the difference.
See here for more info.
If you need to do it in a different thread, take a look on Timer:
int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
time++
}
};
new Timer(delay, taskPerformer).start();
Note that the code above cannot utilize a local variable (they must be declared as final to access them in an anonymous class). It can be a member however.
What you have is rather inefficient, since it wastes CPU cycles waiting for the next wakeup time. If I were you, I'd rewrite the function using Thread.sleep().
As to why your current code doesn't work, your for loop conditions are off, so the loop is never entered.
To have the timer code run concurrently with whatever other logic you have in your program, you'll need to look into threading.
It sounds like you might want to look into multithreading. If you search SO for this, you will find several good question/answer threads. There are also tutorials elsewhere on the web...
Have a look at Timer or better ScheduledExecutorService. They enable you to execute some action periodically and handle the computations surrounding that.
This Morning Class is supposed to create a new Morning, and at the beginning of each a rooster will crow. My rooster will crow once, wait five seconds, and crow again.. Then 5 seconds later it crows twice, and after that it crows non-stop. What could I be doing that makes it do that? I just want it to crow every 5 seconds. If I put a timer.restart() in ActionPerformed, it does nothing. Could someone please point out or give me a tip to what I'm doing wrong? Any help would be much appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
public class Morning extends JFrame
implements ActionListener
{
private EasySound rooster;
public Timer timer;
public Morning()
{
super("Morning");
EasySound rooster = new EasySound("roost.wav");
rooster.play();
timer = new Timer(5000, this);
timer.start();
Container c = getContentPane();
c.setBackground(Color.WHITE);
//page 35
}
public void actionPerformed(ActionEvent e)
{
Morning morning = new Morning();
}
public static void main(String[] args)
{
Morning morning = new Morning();
morning.setSize(300, 150);
morning.setDefaultCloseOperation(EXIT_ON_CLOSE);
morning.setVisible(true);
}
}
You don't have an infinite loop but rather infinite recursion (albeit on the slow side). Don't recurse here -- don't create a new Morning in your Timer's actionPerformed. Instead just put in the method to make the crow sound heard.
Next time, please put your code in your post itself (as I've done for you). Don't make us go to other sites since if you're asking for free help, you want to make it as easy as possible for others to help you.
Edit
You're also shadowing the rooster variable declaring it twice, once int he class which is null and once in the constructor which is not null. Don't redeclare it so you initialize the class field not a local field.
Change this:
public Morning()
{
super("Morning");
EasySound rooster = new EasySound("roost.wav"); // this creates a *local* variable only
rooster.play();
to this:
public Morning()
{
super("Morning");
// EasySound rooster = new EasySound("roost.wav");
rooster = new EasySound("roost.wav");
rooster.play();
Looks to me like you have an infinite loop. You create a new Morning, which starts the timer. When then timer goes off you create a new Morning, which starts the time, etc, etc, etc. Seems like you should be using just a single Morning object that keeps track of how many times it has crowed.
I would suggest setting the Timer to repeat, in actionPerformed crow the appropriate number of times based on how many times it has crowed, and stop the timer when you are crowing forever. This however, assumes that you want exactly 5 seconds between the start of the crows. If you need 5 seconds between the end of a crow and the start of the next, do not repeat but restart the time after you are done crowing.
Instead of instantiating the Morning class each time the timer fires, put the rooster.play() to it (also don't forget to make rooster a class field instead of a local variable). In the constructor, also make sure to call 'timer.setRepeats(true)'