update:demo11

This commit is contained in:
dichgrem
2026-01-14 16:13:53 +08:00
parent 6ce5c76843
commit 1bbfe0e546
4 changed files with 226 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
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();
}
}