[英]Checkbox EventHandler not changing text in label (JavaFX)
我正在學習Java,到目前為止一切進展順利。 我正在學習JavaFX的基礎知識,並編寫了一個僅顯示一些Checkboxes控件和Labels的程序。 我試圖讓Label響應當用戶單擊一個或任何復選框時更改文本。 下面的代碼僅顯示bananaCB的EventHandler復選框。
public class Main extends Application implements EventHandler {
private Label title;
private Label response;
private Label selected;
private CheckBox bananaCB;
private CheckBox mangoCB;
private CheckBox papayaCB;
private CheckBox grapfruitCB;
private String fruits;
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Favorite Fruit");
title = new Label("What fruits do you like?");
response = new Label("");
selected = new Label("");
bananaCB = new CheckBox("Banana");
mangoCB = new CheckBox("Mango");
papayaCB = new CheckBox("Papaya");
grapfruitCB = new CheckBox("Grapfruit");
//Setup the stage and Scene
FlowPane flowPaneRoot = new FlowPane(Orientation.VERTICAL,5,5);
flowPaneRoot.setAlignment(Pos.CENTER);
//We add all of our controls to flowPaneRoot
flowPaneRoot.getChildren().add(title);
flowPaneRoot.getChildren().addAll(bananaCB,mangoCB,papayaCB,grapfruitCB);
flowPaneRoot.getChildren().add(response);
flowPaneRoot.getChildren().add(selected);
//Attach eventListeners to our checkboxes.
Scene scene = new Scene(flowPaneRoot,400,250);
primaryStage.setScene(scene);
primaryStage.show();
}
public void showAll(){
fruits = "";
}
public static void main(String[] args) {
launch(args);
}
@Override
public void handle(Event event) {
Object fruitSelected = event.getSource();
if (bananaCB.equals(fruitSelected)) {
if (bananaCB.isSelected()) {
response.setText("Banana Selected");
} else {
response.setText("Banana cleared");
}
}
}
}
我確實嘗試了setOnAction事件處理程序,它按預期工作。 我在上面的代碼中將其注釋掉,但它弄亂了它的外觀。 我將其張貼在這里。
bananaCB.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
response.setText("Banana Selected");
}
});
我認為正確的條件是bananaCB.ischecked。
試試吧。 標簽可能由於錯誤的方法調用而未更改
您可以將應用程序類的事件作為事件處理程序附加到多個CheckBox
,但是我不建議這樣做。 此外,您實際上需要使用setOnAction
方法注冊處理程序:
bananaCB.setOnAction(this);
mangoCB.setOnAction(this);
...
而且,使用相同的事件處理程序並檢查所有可能的來源是不好的做法。
我建議在這種情況下,對selected
屬性使用ChangeListener
,並為每個CheckBox
使用不同的lambdas / anonymus類:
private static CheckBox createFruitCheckBox(final String text) {
CheckBox result = new CheckBox(text);
ChangeListener<Boolean> listener = (observable, oldValue, newValue) ->
response.setText(newValue ? text + " Selected" : text + " cleared");
result.selectedProperty().addListener(listener);
return result;
}
bananaCB = createFruitCheckBox("Banana");
mangoCB = createFruitCheckBox("Mango");
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.