problem : Use a jlabe to display the number of seconds, and automatically reduce the number by 1 per second
The problem seems very simple, but for beginners of Java, I really took a little effort.
The first is how to do it instantly, and can take a threading approach:
try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} TimeLeft--;
Thread.Sleep (N)
Represents n milliseconds before proceeding to the next step, that is, when n is 1000, stop at this for one second and continue to follow the steps. is equivalent to one second of timekeeping.
How about let JLabel show the time?
In fact, JLabel has such a method:
void SetText (String)
The part that will be displayed becomes a string, and then you can change the contents of the JLabel
That way, you can simply show the time with JLabel:
Package Pra12;import Java.awt.*;import javax.swing.*;p ublic class Simpletimer extends JFrame implements Runnable {int Tim Eleft = 10; JLabel JL = null;public static void Main (string[] args) {//TODO auto-generated method Stubsimpletimer st = new Simpletime R ();} Public Simpletimer () {//TODO auto-generated constructor stubjl = new JLabel (); Jl.settext ("10"); Thread th = new thread (this); Th.start (); This.add (JL); this.setdefaultcloseoperation (Jframe.exit_on_close); This.setsize (max.); This.setvisible (true);} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {try {thread.sleep ()} catch (Interruptede Xception e) {//TODO auto-generated catch Blocke.printstacktrace ();} TimeLeft--;if (TimeLeft = =-1) {timeLeft = 10;} Jl.settext (timeleft+ "");}}}
Show time with JLabel-a difficulty for Java beginners