0

Trying to implement a simple clock into a GUI that will constantly update the time. I've decided to do this by setting a label to the string equivalent of a calendar output, and just sticking that in a while true loop. Problem is when I try to do that the application never opens. No error messages or anything, it just won't open Picture of the console window. I've separated the application into a few seperate java classes: File hierarchy

Code for time setting:

package prototype;

import java.util.Date;


/**
 *
 * @author PC
 */
public class TimeAndDate {
Date date = new Date();

void timedisplay(javax.swing.JLabel a){
String hours = String.valueOf(date.getHours());
String minutes = String.valueOf(date.getMinutes());
String seconds = String.valueOf(date.getSeconds());
while(true){
a.setText(hours + ":" + minutes + ":" + seconds);

    }
}

Code for the main GUI form that uses the above methods.

package prototype;

import javax.swing.JLabel;





/**
 *
 * @author PC
 */
public class MainMenu extends javax.swing.JFrame {

    /**
     * Creates new form MainMenu
     */
    public MainMenu() {
        TimeAndDate time = new TimeAndDate();
        initComponents(); 

        time.timedisplay(dateLbl);

    }

Code works normally if I take the for loop out (but of course then the time won't update). My only guess is that having an infinite loop gives the program too much to try to handle, but I couldn't find anything on that (or dealing with it). Wondering how I might be able to get this clock to refresh. Cheers.

Zak
  • 1
  • 2
  • One word: **timers**. – Kevin Anderson Oct 29 '20 at 14:12
  • I suggest that you add the swing tag to this question. I believe that your problem is that you are blocking the gui thread with your while-loop. You are not allowing anything else to run. Read about using timers with swing and you'll be alright. – NomadMaker Oct 29 '20 at 14:32

0 Answers0