I want to implement a general method of handling clicks for a group of buttons using a switch. I can't get this idea down. With the help of if-else-if

public void onClickTab1Buttons(ActionEvent event){ if (event.getSource() == bt1) { lbl.setText("bt1"); } else if (event.getSource() == bt2) { lbl.setText("bt2"); } else if (event.getSource() == bt3) { lbl.setText("bt3"); } } 

I want something like this:

 public void onClickTab1Buttons(ActionEvent event){ switch (event.getSource()){ case bt1: lbl.setText("bt1"); break; case bt2: lbl.setText("bt2"); break; case bt3: lbl.setText("bt3"); break; } } 

  • Speech is about the implementation of clicks in a JavaFX application: * fxml ... <Button fx: id = "bt1" onAction = "# onClickTab1Buttons" mnemonicParsing = "false" text = "Button1"> ... <Button fx: id = " bt2 "onAction =" # onClickTab1Buttons "mnemonicParsing =" false "text =" Button2 "> ... - Amid

2 answers 2

It is impossible to use such objects in the switch. From the documentation: must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs ...

    Found a solution.

     public void onClickTab1Buttons(ActionEvent event){ Object obj = event.getSource(); Button btn = (Button) obj; switch (btn.getId()){ case "bt1": lbl.setText("bt1"); break; case "bt2": lbl.setText("bt2"); break; case "bt3": lbl.setText("bt3"); break; } } 

    So works