Skip to content

Instantly share code, notes, and snippets.

@TheItachiUchiha
Last active March 31, 2023 07:15
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TheItachiUchiha/12e40a6f3af6e1eb6f75 to your computer and use it in GitHub Desktop.
Save TheItachiUchiha/12e40a6f3af6e1eb6f75 to your computer and use it in GitHub Desktop.
A simple Toggle Switch using JavaFX
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();
}
});
}
}
@TheItachiUchiha
Copy link
Author

To run it, just use it in an Application

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ToggleSwitchDemo extends Application{

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane root = new BorderPane();
        ToggleSwitch button = new ToggleSwitch();
        root.setCenter(button);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
}

@bellaabdelouahab
Copy link

Nice thanks

@969Furqan
Copy link

can you guide me with the fxml implementation?

@khanhsb22
Copy link

Thanks you, it's helpful for me ! :')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment