MyBB Community Forums

Full Version: Java help =P
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Im doing an alarm clock project for my programmig class, and I'm a little stuck. I'm off to a good start(beginner still) but I can't seem to figure out how to make the time update. it takes the value from your computer but doesnt update, heres the code:

import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;



public class  alarmclock1
{

//Getting Time and date info.
  public static String now(String dateFormat) 
    {
    Calendar calen = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    return sdf.format(calen.getTime());
    }

//Starting GUI
  public static void main(String args[]) 
  	{
  		JFrame jf = new JFrame("Alarm Clock");
    	jf.setSize(200,140);									
    	Container c = jf.getContentPane();
    	FlowLayout f1 = new FlowLayout();
    	c.setLayout(f1);
    	JLabel t1 = new JLabel(alarmclock1.now("h:mm a")); //Displays Time
    	JLabel t2 = new JLabel(alarmclock1.now("dd MMMMM yyyy")); //Displays Date
    	JButton b1 = new JButton("Set Alarm"); //Button
    	t1.setFont(new Font("impact", Font.BOLD, 32));
    	t2.setFont(new Font("sansserif", Font.BOLD, 12));
    	b1.setFont(new Font("sansserif", Font.BOLD, 12));
    	c.add(t1);
    	c.add(t2);
    	c.add(b1);
    	//Listener fgl = new Listener();
    	//b1.addActionListener(fgl);
    	jf.setVisible(true);
  	}
}

Any idea how to have it redetect/update? would be very appreciative =P
You probably want to create another thread as a timer which calls an update method every 1 second (see Thread.sleep). The update method would call now() to get the new time, and then t1.setText() and t2.setText() to update the labels.

If you try to sleep the main thread I think your whole program will 'hang' for the 1s.