package com.study.demo11; import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Timer; import java.util.TimerTask; public class EventStatistics extends Frame { private Button clickButton; private Label countLabel; private Label periodLabel; private int clickCount = 0; private DateTimeFormatter formatter; public EventStatistics() { super("事件统计器"); formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); clickButton = new Button("点击"); countLabel = new Label("点击次数:0", Label.CENTER); periodLabel = new Label("统计周期:5秒", Label.CENTER); clickButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { incrementClickCount(); } }); setLayout(new FlowLayout()); add(clickButton); add(countLabel); add(periodLabel); setSize(300, 150); setLocationRelativeTo(null); setVisible(true); startStatisticsTimer(); } private void incrementClickCount() { clickCount++; countLabel.setText("点击次数:" + clickCount); } private void startStatisticsTimer() { new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { LocalDateTime now = LocalDateTime.now(); String statistics = "过去 5 秒内点击次数:" + clickCount; System.out.println(statistics); System.out.println("统计时间点:" + now.format(formatter)); clickCount = 0; countLabel.setText("点击次数:0"); } }, 5000, 5000); } public static void main(String[] args) { new EventStatistics(); } }