-
-
Save nezarjhons/a356cfbe593542c0aecc0ecadc8e6afa to your computer and use it in GitHub Desktop.
A simple Toggle Switch using JavaFX
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
import javafx.beans.property.SimpleBooleanProperty; | |
import javafx.geometry.Pos; | |
import javafx.scene.control.Button; | |
import javafx.scene.control.Label; | |
import javafx.scene.layout.HBox; | |
public class ToggleSwitch extends HBox { | |
private final Label label = new Label(); | |
private final Button button = new Button(); | |
private SimpleBooleanProperty switchedOn = new SimpleBooleanProperty(false); | |
public SimpleBooleanProperty switchOnProperty() { return switchedOn; } | |
private void init() { | |
label.setText("OFF"); | |
getChildren().addAll(label, button); | |
button.setOnAction((e) -> { | |
switchedOn.set(!switchedOn.get()); | |
}); | |
label.setOnMouseClicked((e) -> { | |
switchedOn.set(!switchedOn.get()); | |
}); | |
setStyle(); | |
bindProperties(); | |
} | |
private void setStyle() { | |
//Default Width | |
setWidth(80); | |
label.setAlignment(Pos.CENTER); | |
setStyle("-fx-background-color: grey; -fx-text-fill:black; -fx-background-radius: 4;"); | |
setAlignment(Pos.CENTER_LEFT); | |
} | |
private void bindProperties() { | |
label.prefWidthProperty().bind(widthProperty().divide(2)); | |
label.prefHeightProperty().bind(heightProperty()); | |
button.prefWidthProperty().bind(widthProperty().divide(2)); | |
button.prefHeightProperty().bind(heightProperty()); | |
} | |
public ToggleSwitch() { | |
init(); | |
switchedOn.addListener((a,b,c) -> { | |
if (c) { | |
label.setText("ON"); | |
setStyle("-fx-background-color: green;"); | |
label.toFront(); | |
} | |
else { | |
label.setText("OFF"); | |
setStyle("-fx-background-color: grey;"); | |
button.toFront(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment