I was making a clock, which displays time in Java, I will show the code below:
public class MyApp extends javax.swing.JFrame {
int timeRun = 0;
/**
* Creates new form MyApp
*/
public MyApp() {
initComponents();
System.out.println("We'll start here!");
new Thread ()
{
public void Run(){
while(timeRun == 0)
{
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int AM_PM = cal.get(Calendar.AM_PM);
String time = hour + ":" + min + ":" + sec;
System.out.print(time);
System.out.print("We'll end here!");
}
}
}.start();
}
I have a JLabel, and the other components needed for this JFrame to work.
I also have main set up, although you can't see it in the example above My issue is, that I can't get a value from time, nor can I print "We'll end here" inside the Run, I'm new to Java, so any help would be much appreciated.
My console prints this:
run:
We'll start here!
BUILD SUCCESSFUL (total time: 6 seconds)
You've created a thread, but you haven't overridden the run
method - instead you've created a Run
method. Java is case-sensitive. Change this:
public void Run() {
...
}
to this:
@Override
public void run() {
...
}
Using @Override
asks the compiler to validate that you really are overriding something - if you'd used that before, you'd have received a compile-time error.
Additionally, I'd recommend implementing Runnable
and passing that to the Thread
constructor instead of overriding run
in Thread
itself:
Runnable runnable = new Runnable() {
@Override
public void run() {
...
}
};
new Thread(runnable).start();
Again, if you'd implemented the interface instead of creating an anonymous subclass of Thread
, the compiler would have picked up the problem.
EDIT: As noted in comments, your loop is never-ending, too... but you'll see that when it actually gets as far as running.
See more on this question at Stackoverflow