切换按钮时,背景不会改变

时间:2013-07-13 15:40:06

标签: javafx-2 javafx javafx-8

我想实现此示例:http://docs.oracle.com/javafx/2/ui_controls/toggle-button.htm#

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class test extends Application
{

    private void init(Stage primaryStage)
{
    Group root = new Group();
    primaryStage.setScene(new Scene(root));

    String pillButtonCss = DX57DC.class.getResource("PillButton.css").toExternalForm();

    // create 3 toggle buttons and a toogle group for them
    ToggleButton tb1 = new ToggleButton("Left Button");
    tb1.setId("pill-left");
    ToggleButton tb2 = new ToggleButton("Center Button");
    tb2.setId("pill-center");
    ToggleButton tb3 = new ToggleButton("Right Button");
    tb3.setId("pill-right");

    final ToggleGroup group = new ToggleGroup();
    tb1.setToggleGroup(group);
    tb2.setToggleGroup(group);
    tb3.setToggleGroup(group);
    // select the first button to start with
    group.selectToggle(tb1);

    //////////////////////////////////////////

    tb1.setUserData(Color.LIGHTGREEN);
    tb2.setUserData(Color.LIGHTBLUE);
    tb3.setUserData(Color.SALMON);

    final Rectangle rect = new Rectangle(300, 300);

    group.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
    {
        @Override
        public void changed(ObservableValue<? extends Toggle> ov,
                Toggle toggle, Toggle new_toggle)
        {
            if (new_toggle == null)
            {
                rect.setFill(Color.WHITE);
            }
            else
            {
                rect.setFill(
                        (Color) group.getSelectedToggle().getUserData());
            }
        }
    });


    ///////////////////////////////////////////

    rect.setArcHeight(10);
    rect.setArcWidth(10);

    HBox hBox = new HBox();
    hBox.getChildren().addAll(tb1, tb2, tb3);
    hBox.setPadding(new Insets(20, 20, 260, 20));
    hBox.getStylesheets().add(pillButtonCss);

    VBox vbox = new VBox();

    vbox.getChildren().add(hBox);
    vbox.getChildren().add(rect);

    root.getChildren().add(vbox);
}

@Override
public void start(Stage primaryStage) throws Exception
{
    init(primaryStage);
    primaryStage.show();
}

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

}

但由于某种原因,我可以看到按钮,但是当我尝试切换按钮时,不会显示矩形。你能帮我找到我的错误吗?还有我如何用几个包含不同内容的矩形来实现这个例子?

1 个答案:

答案 0 :(得分:1)

您必须在场景图中添加rect

root.getChildren().addAll(hBox, rect);

另外,请考虑为rootBorderPane而不是Group使用适当的布局。