首页 > 解决方案 > 如何从几个线程读取或修改用户界面上的 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 ---

与往常一样,我们非常感谢任何帮助或指导。

标签: javamultithreadingswinguser-interfacecontrols

解决方案


调用Thread.join()将阻塞,直到线程完成。通过在您的按钮处理程序中调用它,您的按钮处理程序在该过程完成之前不会返回。


推荐阅读