1

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>
Community
  • 1
  • 1
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • There's seems to be a solution here http://stackoverflow.com/questions/8381374/how-to-implement-a-numberfield-in-javafx-2-0 – Alexis C. May 14 '13 at 23:00

1 Answers1

0

If you need to track integer input, you can have a look at the implementation of IntegerField of JavaFX (a field which is used to access only integer values) :

IntegerField.java

IntegerFieldSkin.java

But this approach is not applicable, if CTRL is needed to be tracked.

Alexander Kirov
  • 3,624
  • 1
  • 19
  • 23
  • 1
    Care is recommended in using the IntegerField classes linked in this solution as new versions of JavaFX are not guaranteed to be backward API compatible for private `com.sun` APIs. – jewelsea May 15 '13 at 00:53
  • 1
    You can do your own implementation, using this as basis... – Alexander Kirov May 15 '13 at 09:37