This question already has an answer here:
ToggleButtons and listeners in JavaFX

(1个答案)


3年前关闭。




我有两个切换按钮。


我单击了btn1 // btn1已打开; btn2已关闭
我单击了btn2 // // btn2已打开; btn1自动关闭...为什么?


有人可以解释这种现象并提供解决方案。

我希望所有切换按钮都独立。

最佳答案

如前所述,如果您不将ToggleButton放入ToggleGroup,则可以分别收听切换的selectedProperty

ToggleButton tb1 = new ToggleButton("ToggleButton1");
ToggleButton tb2 = new ToggleButton("ToggleButton2");

tb1.selectedProperty().addListener(((observable, oldValue, newValue) -> {
    System.out.println(tb1.getText() + " changed from " + oldValue + " to " + newValue);
    System.out.println("Taking a nap!");
}));

tb2.selectedProperty().addListener(((observable, oldValue, newValue) -> {
    System.out.println(tb2.getText() + " changed from " +oldValue + " to " + newValue);
    System.out.println("Working hard!");
}));


更新:您也可以使用onActionProperty

for (int i = 0; i< 20; i++) {
    ToggleButton tb = new ToggleButton("ToggleButton"+i);
    tb.setUserData("UserData"+i);
    tb.setOnAction(e -> {
        System.out.println(tb.getText() + " - Selected: " + tb.isSelected()
            + "; UserData: " + tb.getUserData());
    });
}

10-07 16:53