Show time with JLabel-a difficulty for Java beginners

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.