Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. import javafx.beans.property.SimpleBooleanProperty;
  2. import javafx.geometry.Pos;
  3. import javafx.scene.control.Button;
  4. import javafx.scene.control.Label;
  5. import javafx.scene.layout.HBox;
  6.  
  7.  
  8. public class ToggleSwitch extends HBox {
  9.  
  10. private final Label label = new Label();
  11. private final Button button = new Button();
  12.  
  13. private SimpleBooleanProperty switchedOn = new SimpleBooleanProperty(false);
  14. public SimpleBooleanProperty switchOnProperty() { return switchedOn; }
  15.  
  16. private void init() {
  17.  
  18. label.setText("OFF");
  19.  
  20. getChildren().addAll(label, button);
  21. button.setOnAction((e) -> {
  22. switchedOn.set(!switchedOn.get());
  23. });
  24. label.setOnMouseClicked((e) -> {
  25. switchedOn.set(!switchedOn.get());
  26. });
  27. setStyle();
  28. bindProperties();
  29. }
  30.  
  31. private void setStyle() {
  32. //Default Width
  33. setWidth(80);
  34. label.setAlignment(Pos.CENTER);
  35. setStyle("-fx-background-color: grey; -fx-text-fill:black; -fx-background-radius: 4;");
  36. setAlignment(Pos.CENTER_LEFT);
  37. }
  38.  
  39. private void bindProperties() {
  40. label.prefWidthProperty().bind(widthProperty().divide(2));
  41. label.prefHeightProperty().bind(heightProperty());
  42. button.prefWidthProperty().bind(widthProperty().divide(2));
  43. button.prefHeightProperty().bind(heightProperty());
  44. }
  45.  
  46. public ToggleSwitch() {
  47. init();
  48. switchedOn.addListener((a,b,c) -> {
  49. if (c) {
  50. label.setText("ON");
  51. setStyle("-fx-background-color: green;");
  52. label.toFront();
  53. }
  54. else {
  55. label.setText("OFF");
  56. setStyle("-fx-background-color: grey;");
  57. button.toFront();
  58. }
  59. });
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement