JAVAFX event triggered when selecting a check box


Question

My JavaFx FXML application has an issue.

When I select a checkbox on a form, I want to execute a method based on the checkbox that was clicked. Is there any way that I can pass the name of the checkbox through to the method so I can perform some conditional work on it?

I have two checkboxes and only one can be selected. When I click on one, the other should be de-selected and vice versa. Obviously the code below will not work so I am looking to pass the name of the object that was clicked.

Any help would be appreciated, many thanks.

@FXML private void updateRcs(){

    if (chkRcsuri.isSelected()){
        chkRcsuri2.setSelected(false);
    }

    if (chkRcsuri2.isSelected()){
        chkRcsuri.setSelected(false);
    }

}
1
13
9/13/2016 8:29:05 PM

You can use change tracking or use Event handling mechanism of JavaFX.
With checkboxes like this,

final CheckBox chk1 = new CheckBox("chk 1");
final CheckBox chk2 = new CheckBox("chk 2");

Change tracking

chk1.selectedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
        chk2.setSelected(!newValue);
    }
});

chk2.selectedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
        chk1.setSelected(!newValue);
    }
});

Using event handling

EventHandler eh = new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        if (event.getSource() instanceof CheckBox) {
            CheckBox chk = (CheckBox) event.getSource();
            System.out.println("Action performed on checkbox " + chk.getText());
            if ("chk 1".equals(chk.getText())) {
                chk2.setSelected(!chk1.isSelected());
            } else if ("chk 2".equals(chk.getText())) {
                chk1.setSelected(!chk2.isSelected());
            }
        }
    }
};

chk1.setOnAction(eh);
chk2.setOnAction(eh);
26
12/7/2012 9:17:56 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon