Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 out:
            out.setText(String.valueOf(h*r));
            break;
    }
}
like image 424
Fred Avatar asked Mar 16 '26 12:03

Fred


2 Answers

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.

like image 136
Wouter Coekaerts Avatar answered Mar 19 '26 03:03

Wouter Coekaerts


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));
    }
}
like image 27
Joachim Sauer Avatar answered Mar 19 '26 02:03

Joachim Sauer