Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Last active October 20, 2022 05:43
Show Gist options
  • Save julianjupiter/97cdc2154f748ae4b82339bcdd8a2106 to your computer and use it in GitHub Desktop.
Save julianjupiter/97cdc2154f748ae4b82339bcdd8a2106 to your computer and use it in GitHub Desktop.
JavaFX - MVVM - TextField Binding
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextFieldBinding extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
var controller = new Controller();
var scene = new Scene(controller.getVBox(), 200, 200);
primaryStage.setScene(scene);
primaryStage.setTitle("TextField Binding");
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class Controller {
private final VBox vBox = new VBox();
private final ViewModel viewModel = new ViewModel();
Controller() {
this.initialize();
}
public VBox getVBox() {
return vBox;
}
void initialize() {
var filterLabel = new Label("Filter: ");
var filterTextField = new TextField();
filterTextField.textProperty().bindBidirectional(this.viewModel.filterStringProperty());
filterTextField.textProperty().addListener((observable, oldValue, newValue) -> this.viewModel.filter());
var hBox1 = new HBox(filterLabel, filterTextField);
var resultLabel = new Label("Result: ");
var result = new Text();
result.textProperty().bind(this.viewModel.resultProperty());
var hBox2 = new HBox(resultLabel, result);
this.vBox.getChildren().add(hBox1);
this.vBox.getChildren().add(hBox2);
}
}
class ViewModel {
private final StringProperty filterString = new SimpleStringProperty();
private final StringProperty result = new SimpleStringProperty();
public String getFilterString() {
return filterString.get();
}
public StringProperty filterStringProperty() {
return filterString;
}
public String getResult() {
return result.get();
}
public StringProperty resultProperty() {
return result;
}
public void filter() {
var value = this.filterString.getValue();
System.out.println("Filter String: " + value);
this.result.setValue(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment