Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i create a switch button in javafx?

Tags:

java

javafx-2

I want to create a switch button like aboveenter image description here I am a swt developer where i used to get this widget Switchbutton. Can i have something similar in javafx

like image 357
Rajesh Kumar Dash Avatar asked Jul 04 '13 09:07

Rajesh Kumar Dash


Video Answer


2 Answers

First inclination is to extend the JavaFX Label and add a Button as a graphic and a SimpleBooleanProperty for listening. Set an ActionEvent handler on the button that toggles the Label's text, style, and graphic content alignment. The code below will get you started and you can play with styling and bounding.

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; }
}
like image 63
OttPrime Avatar answered Oct 20 '22 00:10

OttPrime


Couldn't this be done with two toggle buttons that are bound together (bind()) where each button get's it's own CSS styling? It actually seems like the CSS would be the tricky (but doable) part to get right.

Then you would just have your app listen to the toggle button of the two that actually does what you want?

like image 30
user2683474 Avatar answered Oct 20 '22 00:10

user2683474