How to set the listener to the textfield value textfield and pass the label reference to it so that the new value is displayed in this label itself?
1 answer
Such options:
In the
textproperty change handler (see the full example below):textField.textProperty().addListener( (observable, oldValue, newValue) -> label.setText(newValue));Through one-way binding of
textproperties:label.textProperty().bind(textField.textProperty());In FXML, using an expression (this is also a one-way binding):
<Label text="${textfield1.text}"/> <TextField fx:id="textfield1" />Also in FXML you can (as suggested by Andrey M ) use
<TextField onTextChange="#method" />and the corresponding method in the controller class. The only thing is that at the moment in Intellij Idea
onTextChangewill be marked erroneous, since this method is not yet implemented in this IDE ( https://youtrack.jetbrains.com/issue/IDEA-184839 ).The same answer shows how to pervert and what is usually done in the controller on java, done through javascript in FXML.
The complete example for 1 (the link to the label in the handler is passed through the closure):
import javafx.application.Application; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class MainLabelFromTextField extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { Label label = new Label(); TextField textField = new TextField(); textField.textProperty().addListener( (observable, oldValue, newValue) -> label.setText(newValue)); Parent root = new VBox(label, textField); stage.setScene(new Scene(root)); stage.show(); } }
label.setText( newValue );- Andrey M