Java如何使用Swing Timer类?
在此示例中,您将看到如何使用java.swing.Timerclass创建文本时钟程序。
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class TimerDemo extends JFrame {
public static final DateFormat df = new SimpleDateFormat("hh:mm:ss");
public TimerDemo() throws HeadlessException {
initUI();
}
private void initUI() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(200, 200);
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));
final JLabel label = new JLabel();
container.add(label);
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
String timeText = "<html><font size=\"6\" color=\"blue\">" +
df.format(now.getTime()) +
"</font></html>";
label.setText(timeText);
}
});
timer.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TimerDemo().setVisible(true);
}
});
}
}
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短