I'm implementing a Timer for different cities using GregorianCalendar class of java.I got a Null Pointer Exception in the following code in ---- target.timeElapsed(this) line.After a lot of practices,I don't got it out.Plzz help me to sort it out..
Here's my code----------
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
TimerTestFrame frame = new TimerTestFrame();
frame.setVisible(true);
}
}
class TimerTestFrame extends JFrame
{
public TimerTestFrame()
{
setSize(450,300);
setTitle("TimerTest");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(2,3));
contentPane.add(new ClockCanvas("San Jose","GMT-8"));
contentPane.add(new ClockCanvas("Taipei","GMT+8"));
contentPane.add(new ClockCanvas("Berlin","GMT+1"));
contentPane.add(new ClockCanvas("New York","GMT-5"));
contentPane.add(new ClockCanvas("Cairo","GMT + 2"));
contentPane.add(new ClockCanvas("Bombay","GMT+5"));
}
}
//implementing a TimeListener interface........
interface TimeListener
{
public void timeElapsed(Timer t);
}
//Timer class which runs in it's seperate Thread..
class Timer extends Thread
{
TimeListener target;
private int interval;
public Timer(int i,TimeListener t)
{
target = t;
interval = i;
setDaemon(true);
}
@Override
public void run()
{
try
{
while(!(interrupted()))
{
sleep(interval);
target.timeElapsed(this);//This line is giving the corresponding error..
}
}
catch(InterruptedException e)
{
}
}
}
//ClockCanvas class having interface TimeListener........
class ClockCanvas extends JPanel implements TimeListener
{
private int seconds =0;
private String city;
private int offset;
private GregorianCalendar calendar;
private final int LOCAL = 16;
TimeListener target;
public ClockCanvas(String c,String tz)
{
city = c;
calendar = new GregorianCalendar(TimeZone.getTimeZone(tz));
Timer t = new Timer(1000,this.target);
t.start();
setSize(125,125);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(0,0,100,100);
double hourAngle = 2 * Math.PI *(seconds - 3 * 60 * 60)/(12 * 60 * 60);
double minuteAngle = 2 * Math.PI*(seconds - 15 * 60)/(60 * 60);
double secondAngle = 2 * Math.PI*(seconds - 15 )/60;
g.drawLine(50,50,50+(int)(30*Math.cos(hourAngle)),50 + (int)(30*Math.sin(hourAngle)));
g.drawLine(50,50,50+(int)(40*Math.cos(minuteAngle)),50 +(int)(40*Math.sin(minuteAngle)));
g.drawLine(50,50,50+(int)(45*Math.cos(secondAngle)),50 +(int)(45*Math.sin(secondAngle)));
g.drawString(city,0,115);
}
public void timeElapsed(Timer t)
{
calendar.setTime(new Date());
seconds = calendar.get(Calendar.HOUR)*60*60 + calendar.get(Calendar.MINUTE)*60 + calendar.get(Calendar.SECOND);
repaint();
}
}
Plzzzzzzz look out through it........ Thanks in advance..