vendredi 24 juin 2016

Weird Behavior of EventHandler MouseClick on CheckBox JFX

Given:

I have a javafx.scene.control.CheckBox and I would like to allow 3-states instead of only 2 (selected and not selected).

I read about indeterminate state.

According to JavaDocs http://ift.tt/28Sg8i4

checked: indeterminate == false, checked == true

unchecked: indeterminate == false, checked == false

undefined: indeterminate == true

Problem:

I need to allow from indeterminate to selected only once

CheckBox checkbox = new CheckBox("Indeterminate");
    checkbox.setAllowIndeterminate(true);
    checkbox.setIndeterminate(true);
    checkbox.setSelected(false);
    checkbox.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                if (checkbox.isIndeterminate()) {
                    checkbox.setSelected(true);
                    checkbox.setIndeterminate(false);
                    checkbox.setAllowIndeterminate(false);
                    checkbox.setText("Checked");
                } else if (checkbox.isSelected()) {
                    checkbox.setSelected(false);
                    checkbox.setText("Unchecked");
                } else if (!checkbox.isSelected()) {
                    checkbox.setSelected(true);
                    checkbox.setText("Checked");
                }
            }
        });

Interestingly, when I click on the checkbox for the first time, it goes directly to the else if (checkbox.isSelected()) block!!!

Question:

WHAT???! HOW? Why isn't this working?

What I need is that if it is initially indeterminate, then on the first click, it should become checked. And continue on more clicks: checked -> unchecked, unchecked -> checked, ...

Else if it initially not indeterminate (ie selected or not selected), then it should behave normally: checked -> unchecked, unchecked -> checked, ...




Aucun commentaire:

Enregistrer un commentaire