开发者

Can I use switch - case, in actionPerformed method in Java

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 o开发者_Go百科ut:
            out.setText(String.valueOf(h*r));
            break;
    }
}


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.


Yes, you can use switch in actionPerformed.

No, you can't use it like you showed it here.

switch only supports primitive types and enums (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));
    }
}


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.


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":
          ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜