I'm new to Java and JavaFX, but I'm trying to build a pretty basic program. Below is a snippet of code I had originally placed in the On Key Pressed
event of the TextField
(it did of course have a different parameter type). However, the code didn't work there (i.e. the user was still allowed to enter characters), and after some Googling I found that maybe this code should be moved to the On Input Method Text Changed
event of the TextField
. But, I'm unable to determine how I can recover the key that was pressed and whether or not CTRL is down.
private void verifyKeyIsInteger(InputMethodEvent event) {
KeyCode code = event.getCode();
if (event.isControlDown() && (code.equals(KeyCode.C) || code.equals(KeyCode.X) || code.equals(KeyCode.V))) {
return;
}
else if (code.isDigitKey()) {
return;
}
event.consume();
}
This code is in my controller that is attached to the FXML
file.
How can I ensure that user's can only input integers into the TextField
?
EDIT
Here is my current FXML
:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="tutoringcalculator.MainFormController">
<children>
<Label layoutX="14.0" layoutY="14.0" text="Session Minutes:" />
<TextField fx:id="sessionMinutes" layoutX="100.0" layoutY="14.0" prefWidth="200.0" />
<Label layoutX="14.0" layoutY="34.0" text="Earnings:" />
<TextField fx:id="earnings" layoutX="100.0" layoutY="34.0" prefWidth="200.0" />
<Button fx:id="quitButton" layoutX="511.0" layoutY="14.0" minWidth="75.0" mnemonicParsing="false" onMouseClicked="#quitApplication" text="Quit" />
</children>
</AnchorPane>