2016-04-26 83 views
1

我在嘗試檢索給定切換按鈕的切換組的「名稱」(或任何類型的唯一標識符),並且一直沒有成功。如果可能的話,重要的是不同的按鈕共享事件處理程序。任何幫助?正在檢索切換組名稱JavaFX

//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

爲什麼不給每個按鈕單獨添加事件處理程序? '#setOnAction'是你正在尋找的功能。您不需要記住切換組。 –

+0

您可以將名稱設置爲userData:'toggleGroup.setUserData(「toggleGroupName」)'。要檢索它,請調用:'String name =(String)toggleGroup.getUserData()' – jns

+0

@jns您可以提交該答案作爲答案,以便標記它嗎?工作完美,謝謝。 –

回答

0

您可以設置名稱作爲用戶數據:toggleGroup.setUserData("toggleGroupName")

要檢索回你撥打:String name = (String) toggleGroup.getUserData()