Java Swing How to - Update JLabel with Timer








Question

We would like to know how to update JLabel with Timer.

Answer

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//  w ww . j  av a  2 s  .  co m
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Main extends JPanel {

  private static final JLabel label = new JLabel("12345678901234567890",
      JLabel.CENTER);

  public Main() {
    this.setLayout(new GridLayout(0, 1));
    this.add(label);
    this.add(new JButton(new AbstractAction("OK") {

      @Override
      public void actionPerformed(ActionEvent e) {
        JButton b = (JButton) e.getSource();
        b.setText("123");
      }
    }));
    new Timer(100, new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        label.setText(String.valueOf(System.nanoTime()));
      }
    }).start();
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setVisible(true);
  }
}