Linda Lay
Linda Lay

Reputation: 21

Timer in JPanel

I'm trying to create an application, and I would like to add a clock. I'm making the Clock using a JPanel and an ActionListener, and would also like to use a Timer. The Swing Tutorial says that to instantiate a Timer, you would say new Timer(numMillis, this(an ActionListener)), however, "this" doesn't seem to work with JPanel items. What would I add to the Timer constructor to properly instantiate the Timer?

public ClockPanel() {
    super();

     clockLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
     clockLabel.setFont(new Font("Monospaced", Font.BOLD, 100));
     clockLabel.setOpaque(true);
     clockLabel.setBackground(Color.black);
     clockLabel.setForeground(Color.white);

     timer = new Timer(500, this);
     timer.setRepeats(true);
     timer.start();

     clockLabel.setVisible(true);

    initComponents();
}
public void actionPerformed(ActionEvent e){
     if(e.getSource().equals(timer))
        clockLabel.setText(sdf.format(new Date(System.currentTimeMillis())));
  }

Upvotes: 0

Views: 3443

Answers (2)

trashgod
trashgod

Reputation: 205885

To avoid leaking this, you can use a nested class that implements ActionListener, as shown in this example.

Upvotes: 3

n00begon
n00begon

Reputation: 3492

I am assuming your ClockPanel looks like:

public class ClockPanel extends JPanel implements ActionListener {

Your action perform appears to be working correctly. If you put a print just before you set the text you will see it is being called. Perhaps you are not refreshing the screen after the text is updated which is why you are not seeing the changes.

Upvotes: 1

Related Questions