我可以在 Java 的 actionPerformed 方法中使用 switch-case
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1667060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use switch - case, in actionPerformed method in Java
提问by Fred
I would like to check on which actionEvent has occurred with ActionEvent eand e.getSource(). Can I use a switch case for this?
我想检查发生了哪个 actionEventActionEvent e和e.getSource()。我可以为此使用开关盒吗?
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;
}
}
回答by Wouter Coekaerts
No, you can't. The types you can use in a switch statement is very limited. See The switch Statement.
不,你不能。您可以在 switch 语句中使用的类型非常有限。请参阅switch 语句。
You can of course just write this as a series of "if" and "else if" statements.
你当然可以把它写成一系列“if”和“else if”语句。
回答by Joachim Sauer
Yes, you can use switch in actionPerformed.
是的,您可以使用 switch in actionPerformed。
No, you can't use it like you showed it here.
不,你不能像你在这里展示的那样使用它。
switchonly supports primitive types and enums (and String, but only in Java 7 and later).
switch仅支持原始类型和enums(和String,但仅在 Java 7 及更高版本中)。
Another problem is that the case-values values must be compile time constants.
另一个问题是 case-values 值必须是编译时常量。
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));
}
}
回答by Adamski
As other solutions have pointed out, you cannot use switch in this context. However, rather than implementing one ActionListenercontaining a big if-then block, why not implement separate ActionListenersfor each event source? This is a much more OO-based approach.
正如其他解决方案所指出的那样,您不能在这种情况下使用 switch。然而,与其实现一个ActionListener包含一个大的 if-then 块,为什么不ActionListeners为每个事件源单独实现呢?这是一种更加基于 OO 的方法。
Typically your ActionListenerimplementations would be (small) anonymous inner classes anyway, and hence you wouldn't have to deal with a huge proliferation of .java files.
通常,您的ActionListener实现无论如何都是(小)匿名内部类,因此您不必处理大量 .java 文件。
回答by Dakshinamurthy Karra
The ActionEventcontains an ActionCommandfield which is a String. If not set while creating the Buttonit defaults to the text of the button. You can use that instead.
的ActionEvent包含一个ActionCommand字段,它是一个字符串。如果在创建时未设置,Button则默认为按钮的文本。你可以改用它。
Something like:
就像是:
switch(e.getActionCommand()) {
case: "Radius":
....
case: "Height":
....
}

