Created
April 13, 2017 09:47
-
-
Save omernaci/0cc67f6afc67c51df50da4ac46517e79 to your computer and use it in GitHub Desktop.
JavaFX Properties and Events Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Counter.java class | |
import javafx.beans.property.IntegerProperty; | |
import javafx.beans.property.SimpleIntegerProperty; | |
/** | |
* | |
* @author omers | |
*/ | |
public class Counter { | |
private IntegerProperty value = new SimpleIntegerProperty(this, "value"); | |
public final IntegerProperty valueProperty() { return value; } | |
public final int getValue() { return valueProperty().get(); } | |
public final void setValue(int i) { valueProperty().set(i); } | |
} | |
// Main.java class | |
import javafx.application.Application; | |
import javafx.beans.value.ChangeListener; | |
import javafx.beans.value.ObservableValue; | |
import javafx.event.ActionEvent; | |
import javafx.event.EventHandler; | |
import javafx.geometry.Insets; | |
import javafx.scene.Scene; | |
import javafx.scene.control.Button; | |
import javafx.scene.control.Label; | |
import javafx.scene.layout.VBox; | |
import javafx.stage.Stage; | |
/** | |
* | |
* @author omers | |
*/ | |
public class Main extends Application{ | |
public static void main(String [] args) { | |
launch(args); | |
} | |
@Override | |
public void start(Stage primaryStage) throws Exception { | |
// Create the counter object | |
final Counter counter = new Counter(); | |
// Create a button to increment the counter value | |
final Button incrementButton = new Button("Increment"); | |
incrementButton.setOnAction((ActionEvent event) -> { // Using lambda expression. | |
counter.setValue(counter.getValue() + 1); | |
}); | |
// Create the label for displaying count | |
final Label countLabel = new Label("Count : "); | |
// I attach a listener to the value property, and update the | |
// label whenever it changes. | |
counter.valueProperty().addListener(new ChangeListener<Number>() { | |
@Override | |
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { | |
countLabel.setText("Count : " + newValue.intValue()); | |
} | |
}); | |
VBox vBox = new VBox(5); | |
vBox.setPadding(new Insets(12)); | |
vBox.getChildren().addAll(countLabel, incrementButton); | |
primaryStage.setScene(new Scene(vBox)); | |
primaryStage.show(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment