检索ToggleGroup名称JavaFX

时间:2016-04-26 03:20:31

标签: java javafx

我正在尝试检索给定ToggleButton的ToggleGroup的“name”(或任何类型的唯一标识符),但一直没有成功。如果可能,重要的是不同的按钮共享事件处理程序。有什么帮助吗?

//create toggleGroups
final ToggleGroup toggleGroup1 = new ToggleGroup();
final ToggleGroup toggleGroup2 = new ToggleGroup();

//create toggleButtons
final ToggleButton toggleButton1 = new ToggleButton("b1");
final ToggleButton toggleButton2 = new ToggleButton("b2");

//assign toggleButtons to toggleGroups
toggleButton1.setToggleGroup(toggleGroup1);
toggleButton2.setToggleGroup(toggleGroup2);

//assign custom handler to toggleButtons
toggleButton1.setOnAction(new handleEvent());
toggleButton2.setOnAction(new handleEvent());

//handler
class handleEvent implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent e) {

        // enable ability to get toggleButton name later
        ToggleButton b = (ToggleButton)e.getSource();

        //get name of group toggleButton belongs too?
        String toggleGroup = b.getToggleGroup().toString();

        // do stuff based on name and group
        if (toggleGroup == "toggleGroup1") {
            //do stuff
        } else if (toggleGroup == "toggleGroup2") {
            //d other stuff
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将名称设置为userData:toggleGroup.setUserData("toggleGroupName")

要将其取回,请致电:String name = (String) toggleGroup.getUserData()