I am building a version of Risk in JavaFX with FXML for school. Now we want to be able to right click a button to decrease the amount of troops in a country and left click it to increase the amount. The left click was pretty self explanatory as it is just an onAction, but how would we check for a right click on a button, through 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>
Advertisement
Answer
To react to a right mouse button click in javaFX, you would use the onMouseClicked
event handler, and in the MouseEvent
, check for which button was pressed using method getButton
, which will return a MouseButton
with value MIDDLE
, PRIMARY
, or SECONDARY
Controller code:
@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">