我可以在 Java 的 actionPerformed 方法中使用 switch - case
我想检查 ActionEvent e
和 e.getSource()
发生了哪个 actionEvent。我可以为此使用开关盒吗?
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;
}
}
I would like to check on which actionEvent has occurred with ActionEvent e
and e.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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,你不能。 switch 语句中可以使用的类型非常有限。
请参阅switch 语句。
当然,您可以将其写为一系列“if”和“else if”语句。
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.
是的,您可以在
actionPerformed
中使用 switch。不,您不能像此处所示那样使用它。
switch
仅支持原始类型和enum
(以及String
,但仅在 Java 7 及更高版本中)。另一个问题是 case-values 值必须是编译时常量。
你需要这样的代码:
Yes, you can use switch in
actionPerformed
.No, you can't use it like you showed it here.
switch
only supports primitive types andenum
s (andString
, 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:
正如其他解决方案所指出的,您不能在这种情况下使用 switch。然而,为什么不为每个事件源实现单独的
ActionListeners
呢?这是一种更加基于面向对象的方法。通常,您的
ActionListener
实现无论如何都是(小型)匿名内部类,因此您不必处理大量的 .java 文件。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 separateActionListeners
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.ActionEvent
包含一个ActionCommand
字段,该字段是一个字符串。如果在创建按钮时未设置,则默认为按钮的文本。你可以用它来代替。像这样的东西:
The
ActionEvent
contains anActionCommand
field which is a String. If not set while creating theButton
it defaults to the text of the button. You can use that instead.Something like: