当前位置: 代码迷 >> J2SE >> java.awt中没法触发事件
  详细解决方案

java.awt中没法触发事件

热度:147   发布时间:2016-04-23 19:51:25.0
java.awt中无法触发事件
import java.awt.*;
import java.awt.event.*;

public class EventTriger extends Frame implements ActionListener{
private Button b1 = new Button("b1");
private Button b2 = new Button("b2");

EventTriger(){
super("EventTriger");
setLayout(new FlowLayout());
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
pack();
setVisible(true);
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
b1.setLabel(e.getActionCommand());//程序运行时,先点击按钮b2,然后b1的标签值会被修改,接着再点击按钮b1,却无法修改b1的标签值
else if(e.getSource()==b2)
this.actionPerformed(new ActionEvent(b1,ActionEvent.ACTION_PERFORMED,Math.random()+" "));
}
public static void main(String[] args){
EventTriger a = new EventTriger();
}
}

代码如上:问题是,程序运行时,先点击按钮b2,然后b1的标签值会被修改,接着再点击按钮b1,却无法修改b1的标签值,按理来说b1的值也会修改成一个随机数
------解决思路----------------------
参考下面这个把actionPerformed()方法修改下,应该就可以达到你要的效果
public void actionPerformed(ActionEvent e) {
/*if (e.getSource() == b1)
b1.setLabel(e.getActionCommand());// 程序运行时,先点击按钮b2,然后b1的标签值会被修改,接着再点击按钮b1,却无法修改b1的标签值
else if (e.getSource() == b2)
this.actionPerformed(new ActionEvent(b1,
ActionEvent.ACTION_PERFORMED, Math.random() + " "));*/
Button b=(Button)e.getSource();
String strRandom=Math.random()+" ";
b=b==b1?b2:b1;
b.setLabel(strRandom);
}
  相关解决方案