0

我需要创建一个RadioButton没有圆圈的自定义。它是一个非常简单的类,可以扩展Label和实现Toggle。我添加了一个鼠标点击处理程序:

private class MouseClickedHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent t) {
            final Toggle toggle = (Toggle) t.getSource();
            if (!toggle.isSelected()) {
                getToggleGroup().selectToggle(toggle);
            }
        }
    }

我的问题是设置一个默认选择的单选按钮。如果在创建后RadioButton我调用其中一个并将其添加到 a 后,当我启动应用程序时,如果我单击组中的其他单选按钮,则会执行取消选择的工作,但默认选项除外。我总是选择 2 个单选按钮,一个是我直接调用 setSelected(true) 的,另一个是当前通过单击选择的。setSelected(true)ToggleGroupToggleGroup

我纠正了它 - 完整的代码:

public class RadioBtn extends Label implements Toggle {

    private ObjectProperty<ToggleGroup> toggleGroup = null;
    private BooleanProperty selectedProperty = null;

    public RadioBtn {
      initHandlers();
    }

    @Override
    public ToggleGroup getToggleGroup() {
        return toggleGroupProperty().get();
    }

    @Override
    public void setToggleGroup(ToggleGroup tg) {
        if (getToggleGroup() == null) {
            toggleGroupProperty().set(tg);
        }
        getToggleGroup().getToggles().add(this);
    }

    @Override
    public ObjectProperty<ToggleGroup> toggleGroupProperty() {
        if (toggleGroup == null) {
            toggleGroup = new SimpleObjectProperty<>();
        }
        return toggleGroup;
    }

    @Override
    public boolean isSelected() {
        return selectedProperty().get();
    }

    @Override
    public void setSelected(boolean bln) {
        selectedProperty().set(bln);
    }

    @Override
    public BooleanProperty selectedProperty() {
        if (selectedProperty == null) {
            selectedProperty = new SimpleBooleanProperty();
        }
        return selectedProperty;
    }


    protected void initHandlers() {
        if (getToggleGroup() != null) {
            setOnMouseClicked(new ToggleGroupHandler());
        }
    }

    private class ToggleGroupHandler implements EventHandler<MouseEvent> {

        @Override
        public void handle(MouseEvent t) {
            final Toggle toggle = (Toggle) t.getSource();
            if (!toggle.isSelected()) {
                /*if(getToggleGroup().getSelectedToggle() != null) {
                    getToggleGroup().getSelectedToggle().setSelected(false);
                }*/
                getToggleGroup().selectToggle(toggle);
            }
        }
    }


}
4

0 回答 0