简体   繁体   中英

How do you erase a label in JavaFX?

When you create a label control in JavaFX, how do you erase it during an event of ie a button click? Here is how I created my Label:

        Label result= new Label("The result is ...");
        root.add(result, 0, 1);

I tried overwriting it with:

        Label result= new Label("");
        root.add(result, 0, 1);

But it doesn't make the previous text go away. It only overwrites the text on the pane.

Thanks.

When you do this:

Label result= new Label("");

You are creating a new Label object. The result is just a variable that points to an object of type Label . Every time you use the keyword new you are creating a new object in the heap, but you are not deleting the old one, that's why it overwrites the text on the pane.

Instead of creating a new Label every time that you want to change the text, create a Label only once, and change the text of this existing Label object by doing this:

result.setText("");

Put this inside of the button's listener:

button.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent event) {
        result.setText("");
    }
});

If you want to erase the content of the label, do:

final Label result = ...
root.add(result, 0, 1);

button.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent event) {
        result.setText("");
    }
});

You can alternatively remove the label; replace the setText() call with:

        result.getParent().getChildren().remove(result);

You may add it again later.

In any case, it has to be final, if declared inside the method. If it is a class member variable, it is OK without final.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM