如何在Button1之后停止Button2和更多运行的操作事件。Button1只需要执行Button1操作事件,然后停止。
请帮帮我,谢谢
public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(button1)){
System.out.println("Button 1");
}
if (ae.getSource() == button2){
System.out.println("Button 2!");
}编辑:
对不起,错误的代码
在main中:
Button1.addActionListener(this);
jPanel1.add(Button1);
Button2.addActionListener(this);
jPanel1.add(Button2);不在main中:
public void actionPerformed(ActionEvent ae) {
Object Button1 = null;
if (!ae.getSource().equals(Button1)){
System.out.println("Oben");
}
Object Button2 = null;
if (ae.getSource() == (Button2)){
System.out.println("Links");
}
}如果我按下我的Button1,我得到"Oben“
如果我按下我的Button2,我也会得到"Oben“
为什么我得不到“链接”
发布于 2013-05-29 23:50:48
您的代码中有两个问题:
将if语句设置为null
actionPerformed调用中运行
试试这个:
public void actionPerformed(ActionEvent ae) {
if(ae.getSource().equals(this.Button1)) {
System.out.println("Button 1");
} else if (ae.getSource().equals(this.Button2)) {
System.out.println("Button 2");
}
}此代码假定Button1和Button2是actionPerformed方法所属类的成员。
发布于 2013-05-29 23:41:29
再看一看你的(编辑过的)代码。
Object Button1 = null;
if (!ae.getSource().equals(Button1)){
System.out.println("Oben");
}所以你在这里说的是下面的,它将在两种情况下求值为真。
if (ae.getSource() != null)这就是为什么结果总是Oben的原因。
如果要与不同的Button1进行比较,请确保引用正确的对象。在看不到其余代码的情况下,很难说,但您可能打算使用(this.Button1);
发布于 2013-05-29 23:54:00
public void actionPerformed(ActionEvent ae) {
Object Button1 = null;
if (!ae.getSource().equals(Button1)){
System.out.println("Oben");
}
Object Button2 = null;
if (ae.getSource() == (Button2)){
System.out.println("Links");
}
}我担心上面的代码没有什么意义,也不符合通常的做法。首先,执行不同操作的按钮应该有不同的侦听器,除非在特殊情况下。这不是那些特例中的一个。将你的代码拆分成:
public void actionPerformed(ActionEvent e)
{
System.out.println("Oben");
// This is the actionPerformed method for button 1.
}
public void actionPerformed(ActionEvent e)
{
System.out.println("Links");
// This is for button 2.
}然后只需绑定到相关按钮即可。
https://stackoverflow.com/questions/16817814
复制相似问题