java - 如何使用定时器和延迟更新 Java Swing GUI?
问题描述
我正在尝试使用 Java GUI 制作排序可视化器。我面临的问题是实时更新 GUI。例如,当我对初始数组进行洗牌时,我将调用以下洗牌和交换方法。我希望它重新绘制 GUI,然后在延迟后再次执行它,但它所做的只是完成 shuffleArray 方法,然后一次重新绘制它,显示没有“动画”。有什么更好的方法来解决这个问题?
public void shuffleArray() {
final int milliDelay = 1000;
for (int i = NUM_BARS - 1; i >= 0; i--) {
int rand = (int) (Math.random() * i);
swap(i,rand, milliDelay);
}
}
public void swap(int firstIndex, int secondIndex, int delay) {
Timer timer = new Timer(delay, e -> {
int temp = data[firstIndex];
data[firstIndex] = data[secondIndex];
data[secondIndex] = temp;
barColors[firstIndex] = Color.RED;
barColors[secondIndex] = Color.RED;
repaint();
barColors[firstIndex] = Color.WHITE;
barColors[secondIndex] = Color.WHITE;
});
timer.setRepeats(false);
timer.start();
}
解决方案
推荐阅读
- ruby-on-rails - Ruby on Rails 模型关系
- go - 如何使用 Redix.v3 将切片插入 Redis 数据库
- css - 如何告诉屏幕阅读器读取属性的值?
- javascript - ParseError:“import”和“export”可能只出现在“sourceType:module”中
- mysql - MariaDB `mysql` 客户端在哪里保存 select 语句的输出文件?
- javascript - 低速数据采样中的 DFT 分析
- flask - 在flask-admin中添加要查看的路线
- ms-access - 如何在记录集中使用两个循环来更新数据
- automationanywhere - 连接到 vpn 后无法访问控制室
- node.js - 转换 tf.fromPixels() 创建的张量时遇到问题