why does it always give the same time?

I used the following program to get the clock.What it turned out to be is a static clock ? Why is it so ?

import java.util.*;
import java.awt.*;
import javax.swing.*;

class tester {

    JFrame fr = new JFrame();
    JPanel p = new JPanel();
    JLabel l = new JLabel();
    Date d = new Date();
    GregorianCalendar gc = new GregorianCalendar();

    tester() {
        p.setBackground(Color.red);
        l.setVisible(true);
        p.add(l);
        fr.add(p);
        fr.setSize(200,200);
        fr.setVisible(true);
        startClockThread();
    }

    public void startClockThread() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                startClock();
            }
        };
        new Thread(r).start();
    }

    public void startClock() {
        l.setVisible(true);  
        while(true) {
            l.setText(gc.get(gc.HOUR) + ":" + gc.get(gc.MINUTE) + ":" + gc.get(gc.SECOND));
            System.out.println(gc.get(gc.SECOND));
        }
    }

    public static void main(String args[]) {
        new tester();
    } 
} 

Answers


GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. Java Doc

You can do this way.

while(true) {
       GregorianCalendar gc = new GregorianCalendar();
   l.setText(gc.get(gc.HOUR) + ":" + gc.get(gc.MINUTE) + ":" + gc.get(gc.SECOND));
}

Now you should understand why you are getting a static clock !


You only create the GregorianCalendar once, and it never gets updated. So the date is always the same.


there's are big problems apart from the one you have spotted:

  • dont let threads run wild, they'll freeze the ui eventually
  • each and every access to a Swing component must happen on the EDT

You can solve both easiest by using a javax.swing.Timer

ActionListener nextSecond = new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
         // get time ...
         timeLabel.setText(...);
     }
}
new Timer(1000, nextSecond).start();

Need Your Help

array_intersect a variable amount of arrays

php arrays variables loops array-intersect

I am creating a faceted search, and I'm am trying to use array_intersect to compare the arrays and find the inputs that match.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.