java - 如何从几个线程读取或修改用户界面上的 java 控件?
问题描述
我会写一个代码摘要,然后我会解释。
我有一个STARTER按钮,可以启动一个程序和一个进度监视器
// from a button
actionPerformed()
// enable procedure control buttons pause and cancel at this point
SomeProcedure ProcTh = new SomeProcedure(aTable)
ProcTh.Start();
ProcessLog LogTh = new ProcessLog(aTable, aProgressBar)
LogTh.Start();
// inside try catch:
ProcTh.join();
LogTh.join();
这是调用过程线程的摘要:
class SomeProcedure extends Thread
JTable aTable = null;
// the executable part
public void run()
for (int i=0;i<aTable.getRowCount();i++)
// process data in a row
while (Paused &&! Canceled)
wait(); // inside a try catch
if (Canceled)
i=aTable.getRowCount()-1; // maybe a break is better??
// the constructor part initializes things
public SomeProcedure (JTable T)
aTable = T;
这是被调用监控线程的总结:
class ProcessLog extends Thread
JTable aTable = null;
JProgressBar aBar = null;
// the executable part
public void run()
while (sofarlong<totallong)
aBar.setValue((int)(sofarlong/totallong));
// also update values in aTable
// the constructor part
public ProgressLog (JTable T, JProgressBar B)
aTable = T;
aBar = B;
我没有编译 ERR,但是当我单击STARTER时,它会挂起,暂停和取消按钮将无法启用。我可能做错了什么。这是从 java 中的线程更新 GUI 控件的最佳方法吗?这是显示另一个线程取得的进展的最佳方式吗?我注意到我无法从线程内部运行访问 GUI 控件,这就是我在创建线程时传递它们的原因。
SomeProcedure 在处理表rown时在 SoFarLong 上写入,而 ProcessLog 只会读取它。SoFarLong 它是 GUI 级别的通用变量,与 SomeProcedure 和 ProcessLog 相同,例如称为 GUI.java ---
与往常一样,我们非常感谢任何帮助或指导。
解决方案
调用Thread.join()
将阻塞,直到线程完成。通过在您的按钮处理程序中调用它,您的按钮处理程序在该过程完成之前不会返回。
推荐阅读
- r - ggplot2 - 拆分一个图例(两个色标)并删除另一个
- sql - 尝试查找 Oracle SQL 中状态字段更改的最近日期
- javascript - Axios + Electron.js 错误:`xhr.js:120 Refused to set unsafe header "user-agent"`
- symfony4 - Symfony 4:将供应商捆绑为“自己的捆绑”以轻松开发?
- java - 同一实体错误的多种表示
- c# - 不确定如何正确地将数据提取到包含字符串、int 和 double 属性的类列表中
- python - 如何从烧瓶启动和停止子进程
- php - 外键约束的格式不正确。你能帮助我吗?
- c# - 如何使用正文表单数据在 Xamarin C# url 中获取数据
- azure - 在 Powershell 中获取 Azure HybridWorker 环境变量