I have created a GUI Java menu using a pull down menu in which I want to have the date and time show up. I am currently getting null for my time value and I think it is because I am not refreshing this each time I calculate my time in my thread, but I'm not 100% sure. I was asked by my instructor to use a thread rather than possibly use the timer function that is available. Any help that can be provided would be greatly appreciated...Here is my code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Test extends JFrame
{
String Current_Date = getDate();
String Current_Time;
getTime a1 = new getTime();
JLabel Date = new JLabel(Current_Date);
JLabel Time = new JLabel(Current_Time);
JMenuItem OptionA = new JMenuItem("Linear Measure");
JMenuItem OptionB = new JMenuItem("Area");
JMenuItem OptionC = new JMenuItem("Temperature");
JMenuItem OptionD = new JMenuItem("Weight");
JMenuItem OptionE = new JMenuItem("Volume and Liquid");
JMenuItem OptionF = new JMenuItem("Speed");
public static void main(String[] arguments)
{
Test frame = new Test();
}
public Test()
{
setLocation(50, 100);
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JMenu ConvT = new JMenu("Conversion Tables " +
// " " +
// Current_Date +
// " " +
// Current_Time);
JMenu ConvT = new JMenu();
ConvT.setText("Conversion Tables " +
" " +
Current_Date +
" " +
Current_Time);
ConvT.add(OptionA);
ConvT.add(OptionB);
ConvT.add(OptionC);
ConvT.add(OptionD);
ConvT.add(OptionE);
ConvT.add(OptionF);
JMenuBar JMB = new JMenuBar();
JMB.add(ConvT);
setJMenuBar(JMB);
setVisible(true);
}
String getDate()
{
String Date;
/* get current Date */
Calendar now = Calendar.getInstance();
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
Date = month + "/" + day + "/" + year;
return Date;
}
public class getTime extends Thread
{
private boolean keepGoing;
String Time;
public getTime()
{
keepGoing = true;
start();
}
private void pause(double seconds)
{
try
{
Thread.sleep((int)(seconds*1000));
} catch (InterruptedException ie)
{
}
}
public void run()
{
while (keepGoing)
{
Calendar c = Calendar.getInstance();
int intHour = c.get(Calendar.HOUR);
int intMinute = c.get(Calendar.MINUTE);
int intSecond = c.get(Calendar.SECOND);
String hour = format(intHour);
String minute = format(intMinute);
String second = format(intSecond);
Test.this.Time.setText(hour + ":" + minute + ":" + second);
//Time = hour + ":" + minute + ":" + second;
pause(1.0);
}
}
/* Verifies the size of an int and adds a leading 0 if */
/* it is smaller than two characters (10). */
String format(int i1)
{
if (i1 < 10)
{
String s2 = "0" + i1;
return s2;
}
return "" + i1;
}
}
}