How can I create a toggle button in javafx?

I want to create a toggle button as above enter image description here I am a swt developer where I used this Switchbutton widget. Can I do something like this in javafx

+6
source share
3 answers

The first slant is to extend the JavaFX Label and add Button as a graph and SimpleBooleanProperty to listen to. Customize the ActionEvent handler on a button that toggles the alignment of Label text, style, and graphic content. The code below will get you started and you can play with style and restriction.

 package switchbutton; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; public class SwitchButton extends Label { private SimpleBooleanProperty switchedOn = new SimpleBooleanProperty(true); public SwitchButton() { Button switchBtn = new Button(); switchBtn.setPrefWidth(40); switchBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { switchedOn.set(!switchedOn.get()); } }); setGraphic(switchBtn); switchedOn.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) { if (t1) { setText("ON"); setStyle("-fx-background-color: green;-fx-text-fill:white;"); setContentDisplay(ContentDisplay.RIGHT); } else { setText("OFF"); setStyle("-fx-background-color: grey;-fx-text-fill:black;"); setContentDisplay(ContentDisplay.LEFT); } } }); switchedOn.set(false); } public SimpleBooleanProperty switchOnProperty() { return switchedOn; } } 
+14
source

Could this be done with two toggle buttons that are connected to each other (bind ()), where each button gets its own CSS style? In fact, it seems that CSS will be the difficult (but doable) part to get it right.

Then you just need your application to listen to the toggle button between the two, what actually does what you want?

+1
source

The FX test project provides the switch button you are looking for.

0
source

Source: https://habr.com/ru/post/948696/


All Articles