建立了一个按钮,按钮上自动更新显示数字。
</pre><pre name="code" class="java">package com.demo;结果如下:按钮上可以自动更新数字,以此为基础可以衍生出倒计时器。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class demo extends JFrame {
private int delay;
private int count;
private JButton jbt = new JButton();
public demo(){
JPanel panel = new JPanel();
int delay = 1000; //milliseconds
panel.add(jbt);
Timer timer = new Timer(delay, new TimerListener());
timer.start();
this.add(panel);
}
private class TimerListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
count++;
jbt.setText(""+count);
jbt.repaint();
}
}
public static void main(String[] args) {
demo mydemo = new demo();
mydemo.setTitle("MyDemo");
mydemo.setSize(200, 200);
mydemo.setLocationRelativeTo(null);
mydemo.setVisible(true);
mydemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}