Reputation: 5
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)
Upvotes: 0
Views: 213
Reputation: 8376
The thread's method you must override is run
. Because that's the one you are inheriting and which is intented to actually run what thread must do.
So:
It's all about inheritance.
Add @Override
annotations in such codes. (IDE should have suggested it).
Remember Java is case sensitive.
Stick to Camel notation. In Java, all is supposed to be coded according to it.
4.1 Classes and Interfaces are supposed to start with capital letters.
4.2 Attributes and methods are supposed to start with small letters.
You should have done:
@Override
public void run() {
//Your code here
}
Upvotes: 1
Reputation: 1500903
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.
Upvotes: 4