Minesweeper countdown timer - java

I am having difficulty with a timer for Minesweeper. timeLabel is a Jlabel for the allowed time remaining in the level, and time is the allowed time (in seconds). The problem is, whenever I restart the game, it will speed up the timer. Does calling the method again when I restart cause this? And what can I do to fix this?
public void addTimer(int t){
time = t;
countDown = new Thread(){
public void run(){
while(time >= 0){
timeLabel.setText(time + "");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
time -= 1;
}
}
};
countDown.start();
}

Related

How to get a method to wait until the timer code has executed?

public void highlightThisText(){
int delay = 1000;
ActionListener tp = new ActionListener(){
public void actionPerformed(ActionEvent ae){
try{
System.out.println();
if(name.equals("Correct")){
thisPanel.getHighlighter().addHighlight(startIndex, endIndex, hl);
}
else{
anotherPanel.getHighlighter().addHighlight(startIndex, endIndex, hl);
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
};
Timer t = new Timer(delay, tp);
t.setRepeats(false);
t.start();
}
I need my program to enter into the highlightThisText method, executed the timer code, and after the delay leave the method. I understand that I cannot use Thread.sleep(1000); as this will block the EDT, but I cannot find any other examples on here with a similar problem. startIndex and endIndex will be incremented after the method is left which means the the correct line will not be highlighted.
Any help will be highly appreciated.

How I create a JProgressBar without reset the values until my method finish

the main problem is that I don't know how long my method will take to finish, I have 2 threads, one to execute the method that do stuff and the other one excute the progress of the progress bar, this is my first thread:
#Override
public void run() {
//This is a static variable, indicate when the method analyzeSentence finish
finish = false;
String sentence = analyzeSentence();
try {
Thread.sleep( 1000 );
} catch (InterruptedException e){
System.err.println( e.getMessage() );
}
finish = true;
}
And in my second thread (the progress bar thread) I have this:
#Override
public void run() {
i = 1;
while(!Analyze.finish) {
i = (i > 100) ? 1 : i+1; //Here I have the problem
progressBar.setValue(i);
progressBar.repaint();
try {
Thread.sleep(this.value);
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
if(Analyze.finish) {
progressBar.setValue(100);
break;
}
}
}
The problem is that the progress bar reset their values to zero but the method still not over so the progress bar is filled again and again... Is there any way to obtain the lenght of the time that the method takes to finish?

Java Thread.sleep() within a for loop

public void playPanel() throws IOException{
for(int i = 0; i<listData.size(); i++){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ascii.setText(listData.get(i));
}
}
What I'm trying to do is play through the listData ArrayList type, which was copied from the ascii JTextArea. Its supposed to be an animation, so when they hit play the function displays the first slide, waits a second, then the next slide, etc.
When I run this the only thing that happens is a pause with nothing on the screen changing until it displays only the final slide. I'm not sure what's wrong with it
You should never call Thread.sleep(...) on the Swing event thread unless your goal is to put the entire application to sleep, rendering it useless. Instead, get rid of the for loop, and "loop" using a Swing Timer. Something like this should work, or be close to a functioning solution (caveat: code has not been compiled nor tested):
int delay = 1000;
new Timer(delay, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (i < listData.size()) {
ascii.setText(listData.get(i));
} else {
((Timer) e.getSource()).stop();
}
i++;
}
}).start();

Android Countdown Timer Thread.sleep();

I am trying to create a circuit timer using the countdown timer. When the thread is sleeping I want the text to display "Change!" and this to display for 5 seconds before the countdown timer starts again. I am unsure how to get this working. I know the thread is sleeping and so wont display the "Change!" until after it has woke up again after the 5 seconds. But I cannot understand how to get it working the way I wish it to. Can anyone help me solve this issue?
public void onFinish()
{
// Text to be displayed when thread is sleeping
time.setText("Change!");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (numberOfCircuits != 15)
{
start();
numberOfCircuits++;
}
else
{
countDownTimer.cancel();
}
}
Instead of making the main thread sleep(you are likely to get an ANR dialog), you can use a Timer which can notify you of your 5sec lapse and you can schedule your CountDownTimer again.
public void onFinish()
{
// Text to be displayed when thread is sleeping
time.setText("Change!");
new Timer("Sleeper").schedule(new TimerTask() {
#Override
public void run() {
if (numberOfCircuits != 15)
{
start();
numberOfCircuits++;
}
else
{
countDownTimer.cancel();
}
}
}, 5000); // 5 sec delay
}

Issue with sleep in Thread

On button click I am calling following function.
private void badButtonHandler() {
Camera.Parameters params = mCamera.getParameters();
params.setColorEffect(Camera.Parameters.EFFECT_NEGATIVE);
mCamera.setParameters(params);
if(thread != null){
thread = null;
}
thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(5000);
Camera.Parameters params = mCamera.getParameters();
params.setColorEffect(Camera.Parameters.EFFECT_NONE);
mCamera.setParameters(params);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
This function is intended to change the Color Effect of Camera after 5 seconds of button click. When pressing the related button for the first time it behaves as expected. But additional calls to this function do not behave as expected. I.e., the second time it waits for 2 seconds, after which it decreases to lower values with every click.
You should not be relying on sleep() as an accurate timer. It won't automatically wake up at the designated time and become the currently active thread, because of the simple fact that all threads are at the mercy of the thread scheduler. Which undoubtedly will vary from OS to OS based on the given JVM.
I have always relied on custom timer functions for these types of scenarios. So, for example:
myTimer(System.nanoTime());
public static void myTimer(long startTime) {
while (startTime + 5000000000 > System.nanoTime()) { //Wait for 5 seconds
try {
Thread.sleep(50); //Sleep at ~50 millisecond intervals
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You won't need to create an entirely new thread as you have done in your example, since Thread.sleep() will put the current thread to sleep. Also, using a while(true) loop is just poor programming practice.
Using nanoTime() is preferred since it is the most precise system timer available in Java.
See this documentation for additional info on the unreliability of the sleep() function.
try this
Thread timer = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//Your desired work
}
}
});
timer.start();

Categories

Resources