How do you erase a label in JavaFX?


Question

When you create a label control in JavaFX, how do you erase it during an event of i.e. 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.

1
1
12/11/2013 8:59:23 AM

Accepted Answer

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("");
    }
});
6
12/11/2013 12:19:13 PM

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.


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