Java - passing variable from FXML ald Java Controller

I make a program using FXML. In FXML I create 4 TextFields and Button. My problem is how send parameters from TextFields in FXML to Controller, when I click this button.

I'm make JavaFX application with FXML. I connect this application to database. I searched for the previous week unsuccessfully, but I found nothing special that can help me.

<children>
    <BorderPane prefHeight="30.0" prefWidth="700.0">
        <bottom>
            <AnchorPane>
                <children>
                    <Button text="Add car" fx:id="button" onAction="#AddCar"/>
                </children>
            </AnchorPane>
        </bottom>
    </BorderPane>
    <TextField promptText="Brand" id="carBrand"/>
    <TextField promptText="Model" id="carModel"/>
    <TextField promptText="Mileage" id="carMileage"/>
</children>

I expect that I click Button in FXML - Java controller get parameters from FXML and write to the console. Actual I know how to write in console, but my problem is that I don't know how to get brand, model and mileage from FXML.

Upvotes: 0

Views: 114

Answers (1)

Slaw
Slaw

Reputation: 45726

You need to inject your TextFields into your controller, then query their text properties. To do this, specify an fx:id for each element to be injected and add a field to your controller class with the same type and name. If the field is not public then you need to annotate it with @FXML.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx/12.0.1" xmlns:fx="http://javafx.com/fxml/1"
      fx:controller="com.example.Controller" spacing="10" alignment="center">
    <TextField fx:id="carBrand" promptText="Brand"/>
    <TextField fx:id="carModel" promptText="Model"/>
    <TextField fx:id="carMileage" promptText="Mileage"/>
    <Button text="Add car" onAction="#addCar"/>
</VBox>

package com.example;

import javafx.fxml.FXML;
import javafx.event.ActionEvent;
import javafx.scene.control.TextField;

public class Controller {

    @FXML private TextField carBrand;
    @FXML private TextField carModel;
    @FXML private TextField carMileage;

    @FXML
    private void addCar(ActionEvent event) {
        event.consume();

        String brand = carBrand.getText();
        String model = carModel.getText();
        String mileage = carMileage.getText();
        // do something with values...
    }

}

Note: Following Java naming conventions, method names use camelCase. In other words, the button's action method's name should be addCar (like above) rather than AddCar.

Upvotes: 2

Related Questions