单选按钮:after
对于MQTT.fx,我想使用ToggleButtons例如选择MQTT消息或QoS级别的解码:
我发现在ToggleGroup的上下文中,ToggleButton在选择/取消选择方面的行为与RadioButtons不同:与RadioButtons不同,ToggleButtons仍可以设置为未选中状态。
RadioButton扩展了ToggleButton并覆盖了fire()(当用户手势指示应为此ButtonBase
发生的事件也称为“单击按钮”时调用):
单选按钮:
@Override public void fire() {// we don't toggle from selected to not selected if part of a groupif (getToggleGroup() == null || !isSelected()) {super.fire();}
}
切换按钮:
@Override public void fire() {setSelected(!isSelected());fireEvent(new ActionEvent());
}
在ToogleGroup中,ToggleButton的行为应类似于RadioButtons,所以恕我直言,这是一个值得对ToggleButton��进行拉取请求的错误。
解决此问题的一种方法是确保创建一个ToggleButton的自定义扩展,以实现与RadioButton有关的fire()。
但是我更喜欢将行为添加到现有控件中。
这是我的修改方式,可以通过向使用了不需要的MouseEvent的ToggleGroup的所有ToogleButtons添加过滤器来修改默认行为:
public class JavaFXUtil {private static JavaFXUtil me;private JavaFXUtil() {}public static JavaFXUtil get() {if (me == null) {me = new JavaFXUtil();}return me;}public EventHandler<MouseEvent> consumeMouseEventfilter = (MouseEvent mouseEvent) -> {if (((Toggle) mouseEvent.getSource()).isSelected()) {mouseEvent.consume();}};public void addAlwaysOneSelectedSupport(final ToggleGroup toggleGroup) {toggleGroup.getToggles().addListener((Change<? extends Toggle> c) -> {while (c.next()) {for (final Toggle addedToggle : c.getAddedSubList()) {addConsumeMouseEventfilter(addedToggle);}}});toggleGroup.getToggles().forEach(t -> {addConsumeMouseEventfilter(t);});}private void addConsumeMouseEventfilter(Toggle toggle) {((ToggleButton) toggle).addEventFilter(MouseEvent.MOUSE_PRESSED, consumeMouseEventfilter);((ToggleButton) toggle).addEventFilter(MouseEvent.MOUSE_RELEASED, consumeMouseEventfilter);((ToggleButton) toggle).addEventFilter(MouseEvent.MOUSE_CLICKED, consumeMouseEventfilter);}}
public class ButtonDemoController {@FXMLprivate ToggleGroup g2;@FXMLprivate ToggleGroup g3;public void initialize() {JavaFXUtil.get().addAlwaysOneSelectedSupport(g2);JavaFXUtil.get().addAlwaysOneSelectedSupport(g3);}}
GitHub上的示例代码。
翻译自: https://www.javacodegeeks.com/2016/04/button-choice-use-togglebuttons-radiobuttons.html
单选按钮:after