java - 在代码运行时更新组件位置?
问题描述
我正在使用 Eclipse WindowBuilder 为我的 Java 程序构建一个 GUI。我目前被卡住了,因为我创建了一个按钮,并且我给 X 和 Y 位置提供了不同的变量。当单击按钮并发出事件时,这些变量会在“While”循环中发生变化。
我试过看多线程。但是,我认为这不是最可行的选择。此外,如果我执行多线程,我不知道我必须将哪一点代码放入单独的线程中。
New button = Button button(X, Y, 100,100);
我正在尝试增加 x 和 Y 坐标
解决方案
Awt 和 Swing 不是线程安全的,因此,如果您尝试在同一个线程中更新 UI,您将出现“应用程序冻结”行为,并且如果您多次单击该按钮,它的位置不会改变。您可以在执行循环的同时禁用该按钮,并且在开始循环之前检查该按钮是否未被禁用。例如:
walkerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
walkerButtonActionPerformed(evt);
}
});
private void walkerButtonActionPerformed(java.awt.event.ActionEvent evt) {
// if walker button is disabled exit the method
if (!walkerButton.isEnabled()) {
return;
}
// Disable the button before starting the loop
walkerButton.setEnabled(false);
int steps = 20;
int stepDistance = 2;
while (steps > 0) {
// Set the walker button new location
int x = walkerButton.getX() + stepDistance;
int y = walkerButton.getY() + stepDistance;
walkerButton.setLocation(x, y);
steps--;
}
// Enable the button after the loop execution
walkerButton.setEnabled(true);
}
另请阅读: Java awt 线程问题 Swing 中的多线程
推荐阅读
- postgresql - Postgres Docker 映像未使用自定义名称创建数据库
- javascript - 从 Azure 时序见解 JavaScript API 查询数据时如何解决 500 内部服务错误?
- python-3.x - 尝试打开放入 S3 存储桶中的 Excel 文件
- swift - 实现一个集合视图 SwiftUI
- jquery - Kendo - 从 localStorage 读取时级联错误
- python - 如何使用 pytest 测试服务是否正常工作
- batch-file - 需要在 .cmd 文件中递归删除目录中所有文件的文件名和文件路径中的空格和双引号
- python-3.x - 从 DataFrame 复制数据并写回 excel?
- ios - 如何对具有透明背景的 WKWebView 进行快照?
- java - 如何检测集合中的循环