Files
Java/com/study/demo11/EventStatistics.java
2026-01-14 16:13:53 +08:00

71 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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();
}
}