Reputation:
I am writing an application for a Java course. I am a complete beginner and am just going off material I have learned from the course and from the web. The application is exhibiting some behavior and I am not sure what is causing it. The application is GUI based and does calculations on user input. For the action listener section, I have a set of If statements such as: "if this button do this if this button do this"
All in a row like that. It seems as if the application is running ALL the if statements instead of running the one that corresponds with the button pressed.
Would I be better off using a case/switch structure for this sort of thing?
I can post my code if necessary, I am new around this site and am not sure if that thing is acceptable.
Upvotes: 1
Views: 292
Reputation: 62789
You probably shouldn't have a single action listener--creating a separate one for each control helps keep your code more readable.
If your controls are sharing a lot of code, however, (the stuff before or after the if statements) then it might make sense to do it that way. In that case, it should be if/elseif.
Also, making your listeners full-fledged classes (rather than anonymous inner classes) can help reuse code as well (the stuff inside each if statement goes into each subclass). This may be beyond what you've learned so far.
Edit: (more direct answer to your actual question)
As far as your problem, the if's should not all execute unless either drs9222's answer that said you were using a semi-colon at the end of your if is correct, or your if statement is testing the wrong thing.
You might just post what you are testing, but you need to compare your known "Button" object to event.getSource() using == or .equals. Since each Button object you are comparing to is different, only one should execute.
Upvotes: 1
Reputation: 4508
Until I see your code I'll have to guess but given your admitted newness you may be writing your if statements like this
if (condition);
{
...
}
instead of like this
if (condition)
{
...
}
Upvotes: 3
Reputation: 16780
Without seeing the code I can't say for sure, but something I always used to do was just use if
and not else if
- if several of my conditions were satisfied, then all of the associated code was run. If you want only the first match to run, use if-else
to ensure that none of the following statements will execute.
Upvotes: 2