How to make checkbox or combobox readonly in JavaFX

前提是你 提交于 2019-12-23 12:45:43

问题


How to make checkbox/combobox readonly in javaFX but not disabled.

I tried consuming onAction event but it didn't work.

checkBox.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        event.consume();
    }
});

Consuming all events like in code below works but I don't think it's a good solution:

checkBox.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        event.consume();
    }
});
checkBox.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEventevent) {
        event.consume();
    }
});

回答1:


You can set the check box to disabled but set the the look of it using CSS. If you are using the default style you can make the check box look 'normal' by setting full opacity.

checkbox.setStyle("-fx-opacity: 1");

It is probably a similar deal with the combo box.




回答2:


You can override method CheckBox#arm() with an empty one:

    CheckBox cb = new CheckBox("hi") {
        @Override
        public void arm() {
            // intentionally do nothing
        }
    };



回答3:


If you do not want to overwrite the CheckBok class, you can use the selectedProperty.

CheckBox cb = new CheckBox("hi");
cb.selectedProperty().addListener(new NCL());



class NCL implements ChangeListener<Boolean> {

        @Override
        public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) {
            cb.setSelected(false);
        }
    }


来源:https://stackoverflow.com/questions/15629775/how-to-make-checkbox-or-combobox-readonly-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!