Thread wont start on Java - java

The following code should produce a regular frame with time in it, when the time hit 90 minutes it should display a message. somehow the Thread wont start and the message Thread is working properly is never displayed. i have already read the following Oracle article but couldn't find any solution.
public class Core extends JFrame implements Runnable{
private int second;
private int minute;
private JLabel presentor;
private Thread threadObject = new Thread();
public Core(){
second = 1;
minute = 0;
presentor = new JLabel();
writeLabel();
add(presentor , BorderLayout.CENTER);
threadObject.start();
}
public void run(){
JOptionPane.showMessageDialog(null, "Thread is working properly");
try{Thread.sleep(60000);}
catch(InterruptedException e){e.printStackTrace();}
updateTime();
writeLabel();
if(minute > 89){
JOptionPane.showMessageDialog(null, "90 minutes have passed away , take a break!");
this.getParent().setFocusable(true);
}
}
public void writeLabel(){
presentor.setText(minute + ":" + second);
}
public void updateTime(){
second++;
if(second < 60)
return;
second = 0;
minute++;
}
}
there is also a class with the Main method which have the basic frame setting, nothing important there.

You didn't specify a Runnable argument for your Thread (which I assume should be this since your Core class implements Runnable):
private Thread threadObject = new Thread(this);

TNT's answer is correct, but it's not complete. Your program has more than one problem. The next problem you will face is that there's no loop in your run() method. It will call updateTime() and writeLabel() exactly once, and then the thread will terminate.
The next problem after that, is in your updateTime() method. It appears as if it's meant to count seconds, but your run() method looks like, if it had a loop, it would only call updateTime() once every minute. That means it will take 90 HOURS, not 90 minutes before your program pops up the dialogue.

Related

Changing the delay of the timer without creating a new one every time the method runs

So basically I have a timer method in my program which uses the integer z as it's parameter as well as the delay for the timer itself. But every time I run this method, it creates a new timer not deleting the old one. So I decided to add an if else block that made it so that it only created a timer on the first time but now it's saying that it might not have been initialized because it was initialized in the if else block. Can someone help me?
public void timer(int z) {
int count = 0;
Timer tester;
z = (60000 / z);
decide = true;
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {noteDecider();}
};
if(count == 0) {
tester = new Timer(z, taskPerformer);
tester.start();
}
else {
tester.setDelay(z);
tester.start();
}
count++;
}
I would say that if you are concern about optimizing your code you should look into optimizing your Timer class. Like moving the ActionListener object inside Timer itself and more. All your timer(int z) method is doing is trying to use an object to keep track time not managing the lifecycle of Timer objects.

Java StopWatch in ChessGame

I have two threads in my ChessGame and I want to implement time control:
Turn of first player: second_thread.stop(), first_thread.run();
counterOfSteps++;
Turn of second player: first_thread.stop(), second_thread.run();
counterOfSteps++;
I have founded many information about Timer but I need Threads.Second thread the same.
There is my code of first thread and it doesn't work because time isn't stopped (System.currentTimeMillis)
first = new Thread() {
#Override
public void run() {
final long time = System.currentTimeMillis();
final long duration = 10800000; //3 hours
while (true) {
try {
Thread.sleep(100);
if (counterOfSteps % 2 == 0) {
System.out.println("Time" + ((duration - (System.currentTimeMillis() - time)) / 1000) % 60);
}
} catch (InterruptedException ex) {
LOG.log(Level.SEVERE, "Unexpected interrupt", ex);
}
}
}
};
How to solve this problem?
Update:
I don't use .stop(). I wrote is for example how to realize.
I have founded many information about Timer but I need Threads.
No. If all you are trying to do is implement a chess clock, then you don't need threads for that. A Timer task that wakes up every second (or every 1/10 second) can;
look at whose turn it is (e.g., counterOfSteps % 2),
compute how much time that player has used, and
Update the appropriate text box in the GUI.
To compute how much time, it'll need to know three things;
What time it is now (e.g., System.currentTimeMillis()),
What time it was when the current turn started, and
How much time the player already had on the clock when the current turn started.
There is no way to pause the system clock (i.e., System.currentTimeMillis()), but that's not a problem. If you sample the clock at the start of each turn, then you can compute the duration of the current turn as System.currentTimeMillis() minus the start time.
I used this example for my quiz, i have 10sec do answer on question this timer decrease int t every 1sec, and set how many times left in some JLabel. You can make 2 object of Timer, first object for first player and second object for second player. You can stop timer when someone finish the move and start second timer...
int t=10
lb2=new JLabel(t);
tim=new Timer(1000,new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(t>0){
t--;
lb2.setText(String.valueOf(t));
}else{
tim.stop();
JOptionPane.showMessageDialog(null, "Time is up");
}
}
});
}

Make a timer in swing

For this game I'm making for java class, I want a timer display in the corner that counts up from 0
I made a variable that represents seconds, which ==> double s =0;
My idea was that using a Timer object where I could increment the variable every second and use the repaint() method on the string
However, I misinterpreted how the timer object works, and after the delay it counts up rapidly to infinity. I have no idea what to do now. A hint would be appreciated.
Here is my code,thanks for any help:
int delay = 5000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
s=(int)s+1;
}
};
new Timer(delay, taskPerformer).start();
String t = "" + s;
g.drawString(t, 100, 100);
repaint();
How about something like this: (you might have to change it for your needs)
boolean temp=true;
long startTime = System.nanoTime();
while(temp){
float time = (System.nanoTime()-startTime)/ 10000000.000f;
System.out.println(time);
}
What you can try doing is implementing the Runnable interface and then starting a new Thread of the class that you are using to draw your Components. Since Thread implements the Runnable interface, you will be able to create a new point of execution in the program where you can call a delay with Thread.sleep() before repainting your components. Here is an example of what you should try doing:
Thread thread = new Thread(ClassNameHere);
thread.start();
If you are interested in trying this out, more information can be found on the API on Threads and on the Runnable interface.

Display delayed text on User's screen

Hello!
I am trying to display a text on the Screen (with Java), but I want it to be delayed, like, every 0.1 seconds, a letter of the text would appear on the screen. It's like Pokemons dialogs. Here's what I am talking about: https://www.youtube.com/watch?v=yUS1IcC5CBY
I don't want the fade and the acceleration of the text, I just want the text to appear letter-by-letter. Also, I would like the text to be a String. Please, can you help me?
Thanks a lot in advance!
You can use two methods:
One is Thread.sleep(), which is shown above:
private static String message = "Your Message";
private static JLable label = new JLabel();
private static String labelMessage = "";
for(int i = 0; i < message.length(); i++){
labelMessage += Character.toString(message.charAt(i));
label.setText(labelMessage);
try{
Thread.sleep(howManyMillisecondsYouShouldWait);//if you want to do it every .1
//seconds, just wait 100 milliseconds.
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
that will forever print it to the screen every 100 milliseconds. However, the only trouble with using Thread.sleep is (and I somehow just learned this the other day, even though I've been programming for a long while) it is not always accurate. It may sleep 100 ms, it may sleep 150, etc. Secondly, a slower computer may take longer to sleep through it.
The other method which you will use more often (probably) is to check the actual time of your system and see if it's been long enough since you last printed it to the screen, like this:
private static long timeOfLastWrite;//at what time did you last update the text?
private static long deltaTimeSinceLastWrite;//how long has it been since you last updated the text?
private static long timeOfFirstWrite;//when did you start?
private static long deltaTimeSinceFirstWrite;//how long has it been since you started?
private static String message = "Your Message";
private static JLabel label = new JLabel();
private static String labelMessage = "";
//print once here:
timeOfFirstWrite = System.currentTimeMillis();
timeOfLastWrite = System.currentTimeMillis();//every time you print to the screen, make
//sure that you make note of it by setting the timeOfLastWrite variable equal to the current time.
labelMessage += Character.toString(message.chatAt(0));
while(!labelMessage.equals(message)){
deltaTimeSinceLastWrite = System.currentTimeMillis() - timeOfLastWrite;
if(deltaTimeSinceLastWrite >= 100){
timeOfLastWrite = System.currentTimeMillis();
deltaTimeSinceFirstWrite = System.currentTimeMillis() - timeOfFirstWrite;
int currentIndexOfChain = (int) deltaTimeSinceFirstWrite / 100;
if(currentIndexOfChain >= message.length()){
currentIndexOfChain = message.length() - 1;
}
labelMessage = message.substring(0, currentIndexOfChain + 1);
label.setText(labelMessage);
}
}
This method isn't even slightly necessary for a program so simple as writing text to the screen 10 times a second. However, it's good to get into the practice of it. You'll learn that if you create a character and tell him to move 10 pixels, Thread.sleep(100), and move again and etc... that on a slower computer, the character will move slower. However, if you tell it to wait until a certain amount of time has passed according to your computer's time, if the user lags out and it takes 200 milliseconds before it tells the character to move again, you can account for that by simply making him move twice as far -- I think it's called framerate independence.
If I did anything wrong with the delta time management please let me now. Again, I just learned about this the other day even though I've been programming for awhile, so don't worry about it too much if you're just now learning to program.
And that's how you make an incredibly long (possibly too long) answer to an incredibly simple question. I hope you benefit from this response.
I'm unable to use Thread.sleep(x) or wait(): java.lang.InterruptedException; must be caught or declared to be thrown
try {
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
You may use this code for doing so. Simply put a thread to print the text onto a jLabel.
new Thread(new Runnable() {
#Override
public void run() {
String x="";
String txt="Hello this is a sample text. Let us see how this works.";
for(int i=0;i<txt.length();i++){
try {
jLabel1.setText(x=x+txt.charAt(i));
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}).start();
How about this?
import javax.swing.Timer;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DelayText
{
public String example = "As you can see, this sentence is being printed out a character at a time.";
public String transfer = "";
public Timer t;
public int i = 0;
public JFrame f;
public JLabel l;
public DelayText()
{
f = new JFrame("Example");
l = new JLabel();
f.add(l);
f.setSize(450, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
TimerListener tl = new TimerListener();
t = new Timer(100, tl);
t.start();
}
public static void main(String[] args)
{
DelayText d = new DelayText();
}
private class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(i < example.length())
{
transfer += (example.charAt(i));
l.setText(transfer);
i++;
}
if(i >= example.length())
{
t.stop();
}
}
}
}
I am using the timer to create a delay between each character outputted on the JFrame. I noticed a lot of these other ones were a bit more complex, thought this might make things a bit easier to understand.

I want to add timer in my applet

I made CountDown.java file and try to add in my Word-trouble.java file (which is main applet) as CountDown ct = new CountDown();
but it is not showing timer in main applet.
Here is coding:
package pack.urdu;
import java.awt.*; //windows toolkit
import java.applet.*; //applet support
public class CountDown extends Applet implements Runnable{
int counter; Thread cd;
public void start() { // create thread
counter = 60; cd = new Thread(this); cd.start();
}
public void stop() { cd = null;}
public void run() { // executed by Thread
while (counter>0 && cd!=null) {
try{Thread.sleep(1000);} catch (InterruptedException e){}
--counter; repaint(); //update screen
}
}
public void paint(Graphics g) {
g.drawString(String.valueOf(counter),25,75);
}
}
You are making a mistake that I see a lot of programmers make: you are mixing up the calculation of elapsed time, with the calculation of the refresh time. If the duration of sleep takes long than a second because of thread contention, your timer will drift.
Instead of tracking a counter that increments every second, just record the start time:
long startTime = System.currentTimeMillis();
Then later, your paint method becomes:
public void paint(Graphics g) {
int elapsedSeconds = (int)(System.currentTimeMillis()-startTime)/1000
g.drawString(String.valueOf(elapsedSeconds),25,75);
}
This method can be called as often, and as many times as you like, and it will always display the correct elapsed seconds. There is no need to increment anything at any specified time.
The only other thing you have to do is to arrange that the screen gets refreshed. (I like to say that you only have to refresh the screen when the user looks at it :-) but since we don't know that we need to refresh more often). The mechanism for this may depend upon the graphic library. One lazy idea is to refresh ten times a second and the screen will be right most of the time.
If you do want to have a thread that sends repaint events, you should have those events sent just at the time that timer clicks over to a new value, and thereby send only one per second. This is done with:
while (stillRunning) {
long elapsedTime = System.currentTimeMillis() - startTime;
long timeTillNextDisplayChange = 1000 - (elapsedTime % 1000);
Thread.sleep(timeTillNextDisplayChange);
repaint();
}
Note that you do not sleep 1000ms! If your system is performing well, this will be very close to 1000ms, but slightly less than that to account for (1) the thread startup delay, possibly caused by thread contention, and (2) the processing time for this loop (which is quite small). In any case, calculating the sleep in this way will prevent timer drift, and assure that your display updates just as the seconds value changes.
See an extended discussion of Common Misunderstandings of Timers on my website.

Categories

Resources