如何在javafx中创建一个开关按钮?

Raj*_*esh 6 java javafx-2

我想创建一个像上面那样的开关按钮在此输入图像描述 我是一个swt开发人员,我曾经在这里获得这个小部件Switchbutton.我可以在javafx中使用类似的东西吗?

Ott*_*ime 14

第一个倾向是扩展JavaFX Label并添加Button一个图形和一个SimpleBooleanProperty用于监听.ActionEvent在按钮上设置一个处理程序,用于切换Label文本,样式和图形内容对齐.下面的代码将帮助您入门,您可以使用样式和边界.

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; }
}
Run Code Online (Sandbox Code Playgroud)