0

I am fairly new to java. I want to update a button's text using a class so when the method is called it updates accordingly. I've tried to implement some of the code from other relevant posts but can't figure it out. First of all - do you have to update the whole scene in order to update a button or does it work like react where it updates parts of the DOM?

The goal is to update the text of the button when the scene loads. FXML file:

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="project.Controller">
<Button fx:id="button" text="STOP"></Button> 
</AnchorPane>

Primary Java file:

public class project extends Application { 
    @Override
    public void start(Stage primaryStage) throws Exception {

        try {

            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(project.class.getResource("index.fxml"));
             Parent root = loader.load();

            Scene scene = new Scene(root, 1200, 750);

            primaryStage.setScene(scene);
            primaryStage.show();

            Controller editButton = new Controller();
            editButton.editButtonText("blabla selected");


        } catch (Exception e){
            System.out.println(e);
        }  
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Class file:

public class Controller implements Initializable
{   

    //FXML
   @FXML public Button button;


   @FXML
   public void editButtonText(String text){
    //   button = new Button();
       button.setText(text);
   }

   @Override
   public void initialize(URL url, ResourceBundle r){

   }
}

1 Answers1

3
Controller editButton = new Controller();
editButton.editButtonText("blabla selected");

The problem is that part. Once you load the fxml file with the FXMLLoader, a new controller object is automatically created. You can access that controller object by using

Controller editButton = (Controller) loader.getController`

Otherwise you reference a new Conctroller, that doesn't have a GUI assigned to it.

Alternatively, you could also write it as:

Controller controller = new Controller();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(project.class.getResource("index.fxml"));
loader.setController(controller);
Parent root = loader.load()

That way, your newly created Controller object is set as the FXMLController for the fxml file you are about to load. Notice: for this to work, the controller can not be set in the fxml file.

AdminOfThis
  • 191
  • 3