Can I use switch - case, in actionPerformed method in Java
Solution 1
Yes, you can use switch in actionPerformed
.
No, you can't use it like you showed it here.
switch
only supports primitive types and enum
s (and String
, but only in Java 7 and later).
Another problem is that the case-values values must be compile time constants.
You'll need code like this:
public void actionPerformed(ActionEvent e){
if (e.getSource() == radius) {
double r = validate(radius.getText());
else if (e.getSource() == height) {
double h = validate(height.getText());
else if (e.getSource() == out) {
out.setText(String.valueOf(h*r));
}
}
Solution 2
No, you can't. The types you can use in a switch statement is very limited. See The switch Statement.
You can of course just write this as a series of "if" and "else if" statements.
Solution 3
As other solutions have pointed out, you cannot use switch in this context. However, rather than implementing one ActionListener
containing a big if-then block, why not implement separate ActionListeners
for each event source? This is a much more OO-based approach.
Typically your ActionListener
implementations would be (small) anonymous inner classes anyway, and hence you wouldn't have to deal with a huge proliferation of .java files.
Solution 4
The ActionEvent
contains an ActionCommand
field which is a String. If not set while creating the Button
it defaults to the text of the button. You can use that instead.
Something like:
switch(e.getActionCommand()) {
case "Radius":
....
case "Height":
....
}
Fred
Updated on June 13, 2022Comments
-
Fred over 1 year
I would like to check on which actionEvent has occurred with
ActionEvent e
ande.getSource()
. Can I use a switch case for this?public void actionPerformed(ActionEvent e){ switch(e.getSource()){ case radius: double r = validate(radius.getText()); break; case height: double h = validate(height.getText()); break; case out: out.setText(String.valueOf(h*r)); break; } }
-
Jonathan Feinberg about 14 yearsYou can also switch on Enums.
-
Fred about 14 yearsThanks, to bad. So I guess I can't use switch, case then.
-
Khyar Ali about 14 yearsAre Strings really allowed in switch? I though it's comming only in Java 7, no?
-
Fred about 14 yearsThanks for the link. It's good to know, I wanted to ask to be sure there wasn't some way around it before abandon it for, 'if, else'.
-
jezg1993 about 14 yearsJosh Bloch made a push for it but I havent heard anything
-
Anthony Fammartino about 14 yearsJava 7 will allow Strings for switch, as part of Project Coin. It is not allowed in previous versions.
-
Joachim Sauer about 14 years@Jonathan: yes, I got mixed up in my explanation of what compile time constants can be. Strings are of course not valid in a switch, I tried to clarify that in my answer.