Reputation: 13
How do I stop the action event of Button2 and more runs after Button1. Button1 need to do only Button1 Action Event and stop then.
Please Help me, thank you
public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(button1)){
System.out.println("Button 1");
}
if (ae.getSource() == button2){
System.out.println("Button 2!");
}
edit:
sorry, wrong code
in main:
Button1.addActionListener(this);
jPanel1.add(Button1);
Button2.addActionListener(this);
jPanel1.add(Button2);
not in 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");
}
}
if i press my Button1, i get "Oben"
if i press my Button2 i get "Oben", too
why i dont get "Links"
Upvotes: 0
Views: 859
Reputation: 27346
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");
}
}
I'm afraid the above code make's little sense, and doesn't conform to usual practice. Firstly, buttons that perform different actions should have different listeners, except in special cases. This is not one of those special cases. Split up your code into:
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.
}
Then simply bind to the relevant buttons.
Upvotes: 1
Reputation: 1915
There are two problems in your code:
Button1
and Button2
to null
actionPerformed
Try this:
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");
}
}
This code assumes that Button1
and Button2
are members of the class that the actionPerformed
method belongs to.
Upvotes: 1
Reputation: 3456
Take another look at your (edited) code.
Object Button1 = null;
if (!ae.getSource().equals(Button1)){
System.out.println("Oben");
}
So what you're saying here is the following, which is going to evaluate true in both cases.
if (ae.getSource() != null)
This is why the result is always Oben.
If you are intending to compare against a different Button1
, make sure to reference the correct the object. Without seeing the rest of the code it's hard to say, but you may mean to use (this.Button1
);
Upvotes: 1