有没有办法检查 FXML 中的鼠标右键单击?

Is there a way to check for a right mouse button click in FXML?

我正在为学校构建一个使用 FXML 的 Risk in JavaFX 版本。现在我们希望能够右键单击一个按钮来减少一个国家的军队数量,然后左键单击它来增加数量。左键单击是不言自明的,因为它只是一个 onAction,但是我们如何通过 FXML 检查按钮上的右键单击?

<Button id="ontario" fx:id="ontario" layoutX="356.0" layoutY="145.0" mnemonicParsing="false" onAction="#countryPressed" prefHeight="40.0" prefWidth="40.0" styleClass="CountryButton" stylesheets="@style.css" 
    <font>
        <Font name="System Bold" size="16.0" />
    </font>
</Button>

要在 javaFX 中对鼠标右键单击做出反应,您可以使用 onMouseClicked 事件处理程序,并在 MouseEvent 中使用方法 getButton 检查按下了哪个按钮,这将 return 一个值为 MIDDLEPRIMARYSECONDARY

MouseButton

控制器代码:

  @FXML
  public void buttonClicked(MouseEvent event) {
      switch (event.getButton()) {
      case PRIMARY: //Left button
          //Do something
          break;
      case SECONDARY: //Right button
          //Do something else
          break;
      default:
          //Ignore
          break;
      }
  }

FXML:

<Button fx:id="ontario" onMouseClicked="#buttonClicked">