关于button事件执行多个方法,依次将结果返回的问题

syj247 2014-08-15 08:00:36
在gui中有一个按钮,有三个方法 methodA(),methondB(),methondC()返回值都是String

需求是点击button1后,执行methondA(),并将methodA()的返回值作为button1的Text;继续执行methodB(),更新button1的Text,再执行methodC,更新button1的Text

我的代码如下


@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {

jt.setText(method1());
jt.setText(method2());
jt.setText(method3());
}
}

private string methodA(){
//todo something
System.out.println("方法1被执行");
return "方法一被执行";
}
private string methodB(){
//todo something
System.out.println("方法2被执行");
return "方法二被执行";
}
private string methodC(){
//todo something
System.out.println("方法3被执行");
return "方法三被执行";
}

效果是methondA(),methodB(),methodC(),依次被执行,但是methodA,methodB的返回值未成功的设置为button的Text.
说明:methodA(),methodB()方法中处理的事务非常多。不存在运行太快肉眼无法发现。

...全文
83 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
syj247 2014-08-15
  • 打赏
  • 举报
回复
引用 1 楼 skgary 的回复:
那是因为 1. 你的函数还没有返回,当然是不会更新UI的。 2. 你在主线程里做事事情,会产生no response 如果要实现你的效果 1. 增加一个Handler,只用于更新UI 2. 几个方法必须放在线程中执行, 3. 完成一个方法后,向handler post消息,通知handler进行更新。
我改成

@Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button1) {
            Thread myThread = new Thread(){
                 @Override
                 public void run(){
                     jt.setText(method1());
                    jt.setText(method2());
                    jt.setText(method3());
                 }
           }

                myThread.start();
               
        }
  }

就可以了,没有手动去更新UI 非常感谢楼上,解决我困扰了3天的问题。万分感激。
skgary 2014-08-15
  • 打赏
  • 举报
回复
那是因为 1. 你的函数还没有返回,当然是不会更新UI的。 2. 你在主线程里做事事情,会产生no response 如果要实现你的效果 1. 增加一个Handler,只用于更新UI 2. 几个方法必须放在线程中执行, 3. 完成一个方法后,向handler post消息,通知handler进行更新。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧