Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Q.2. Using the javax.swing.

Timer together with the ActionListener for event handling, display a digital clock in an
Applet.
In the init() method, initialise the clock to 00:00. In the start() method, display the system time.

CODE:

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.Timer;
/**
*
* @author shaunak
*/
public class Digital extends JApplet implements ActionListener
{
private JLabel label;
int hours=0,minutes=0,seconds=0;
Timer t;
public void start()
{
t.start();
}
public void init()
{
t=new Timer(0,this);
label=new JLabel("00:00:00");//initializes label
Container myContainer = getContentPane();
myContainer.setLayout(new FlowLayout());
myContainer.add(label);

}
public void actionPerformed(ActionEvent e)
{
StringBuffer str=new StringBuffer();
Calendar cal = Calendar.getInstance();
hours=cal.get(Calendar.HOUR_OF_DAY);
str.append(hours+":");
minutes = cal.get(Calendar.MINUTE);
str.append(minutes+":");
seconds = cal.get(Calendar.SECOND);
str.append(seconds);
label.setText(str.toString());
}
public void stop()
{
t.stop();
}
}

OUTPUT:

You might also like