How to Retrieve Data from a Text Field in JavaFX

Java


In this article, we show how to retrieve data from a text field in JavaFX.

A text field is a field where a user can type something into, such as his or her name, phone number, email, etc.

We create a text field by creating an instance of the TextField class. We then retrieve the value using the object name followed by a dot and the getText() method.

In the code below, we create a single text field named text.

We then retrieve the value through the line, text.getText();

The full code is shown below.



So just like any JavaFX application, you need to import several packages. You're more than likely familiar with this.

We then create a class that extends the Application. Therefore, we inherit all the functionality of the Application class, which has a lot of classes and methods that we need to use.

We then override the start() method, which is present in the Application class.

The start() method contains the main functionality of the program.

The stage is primaryStage.

All JavaFX applications must have at least one stage.

We set the title to "Customer Information".

We then create a label, asking for the user's name.

We then create a second label named labelresponse. This is blank right now but later on in the code we will set this value based on the name that the user gives.

We then create a button named button and give it a surface text value of "Submit". Basically the button is just a typical submit button.

The next line is very important. It adds event handling to the button, so that when a user clicks on the button, we can do whatever we want to do. What we do in this program is we output a statement once the user clicks the submit button, telling the user what name s/he has entered.

The e paramters acts as an event handler. When a user clicks on the button, the label named labelresponse is set to "The name you entered is " followed by the name entered thorugh the setText() function. Therefore, if a user enters in the name David, the statement, "The name you entered is David".

This is shown at the following link: JavaFX Text Field.

We get the value that the user has entered into the text field by the line, text.getText(); Since the text field ha a name of text, this is why text is used.

We then create our layout for the window. We create a VBox layout, meaning the elements are vertically stacked, 5px apart.

We then add all of our components to the layout, create the scene, set the scene to the stage, and then show the stage.

And this is all that is required to retrieve data from a text field in JavaFX.


Related Resources

How to Retrieve Data from a Radio Button Group in JavaFX

How to Retrieve Data from a Group of Check Boxes in JavaFX

How to Retrieve Data from a ChoiceBox in JavaFX




HTML Comment Box is loading comments...