当前位置: 代码迷 >> J2SE >> 关于button事件执行多个方法,依次将结果返回的有关问题
  详细解决方案

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

热度:100   发布时间:2016-04-23 20:24:02.0
关于button事件执行多个方法,依次将结果返回的问题
本帖最后由 syj247 于 2014-08-15 08:02:30 编辑
在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()方法中处理的事务非常多。不存在运行太快肉眼无法发现。


------解决方案--------------------
那是因为
1. 你的函数还没有返回,当然是不会更新UI的。
2. 你在主线程里做事事情,会产生no response

如果要实现你的效果
1. 增加一个Handler,只用于更新UI
2. 几个方法必须放在线程中执行,
3. 完成一个方法后,向handler post消息,通知handler进行更新。
  相关解决方案