0

我想实现这个例子: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);
}

}

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

4

1 回答 1

1

您必须添加rect到场景图中:

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

root另外,请考虑为您的,BorderPane而不是Group例如使用适当的布局。

于 2013-07-13T16:57:08.220 回答