Home > database >  JavaFX Replace new Text with old one without overwriting it in the scene
JavaFX Replace new Text with old one without overwriting it in the scene

Time:10-24

I'm pretty new to Java and in the second month of my training. So i want every time i press "New" that the old text deletes and then the new one comes. but that doesn't happen. i already looked on the internet and didn't find anything.

when i press "new" then just new text comes over the old text. i thought if i make text(null) before it then it deletes it. but it doesn't work.

this is what i get if i press the button more times: image

thanks for helping me im lost

heres my code:

    buttonNew.setOnAction(new EventHandler<ActionEvent>() {


    @Override
    public void handle(ActionEvent arg0) {
        
        int randomM1=(int)(Math.random()*11);
        int randomM2=(int)(Math.random()*11);
        
        
        System.out.println(randomM1   " x "   randomM2);
        
        System.out.println(randomM1 * randomM2);
            
        
        Text mText = new Text();
        mText.setText(null);
        mText.setText(randomM1   " x "   randomM2);
        rootM.getChildren().add(mText);
        mText.setLayoutX(300);
        mText.setLayoutY(200);
        mText.setFont(Font.font("Verdana",50));
        
        
    }
}); 
    

CodePudding user response:

You are creating a new Text on every button click, and adding this new Text into rootM every time.

When you say mText.setText(null); you are clearing the text of the newly created mText variable, which is different from the one already added to the layout.

To overcome this, you can define the Text variable once outside the event handler, and just update its text when needed.

final Text mText = new Text();
rootM.getChildren().add(mText);
mText.setLayoutX(300);
mText.setLayoutY(200);
mText.setFont(Font.font("Verdana",50));

buttonNew.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent arg0) {
        // your code to generate random ...

        mText.setText(randomM1   " x "   randomM2);
    }
}); 
  • Related