Search code examples
javafxjavafx-8

how to get access to the field of already launched application


inside controller there is a TextArea

the application to check if it is already running just exits without letting another instance start

    public class Main extends Application {

    private static Controller controller;

    @Override
    public void start(Stage primaryStage) throws Exception{

    FXMLLoader fxmlLoader = new FXMLLoader();
    AnchorPane anchorPane = fxmlLoader.load(getClass().getResource("sample.fxml"));
    primaryStage.setScene(new Scene(anchorPane));
    primaryStage.setTitle("Hello World");
    primaryStage.show();
}

public static void main(final String[] args) throws IOException {

    if (Application Launch)) {
       //how to access the open application


       FXMLLoader fxmlLoader  = new FXMLLoader(getClass().getResource("sample.fxml"));
       controller = fxmlLoader.getController();
       controller.doSomeThing("myText");

        System.exit(0);
    }else {
        launch(args);
    }

that is a controller

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;

public class Controller {
@FXML
private TextArea textArea;

public void doSomeThing(String myText) {
    textArea.setText(myText);
}
}

Solution

  • So a small example for you:

    private static Controller controller;
    
    
    FXMLLoader fxmlLoader  = new FXMLLoader(getClass().getResource("sample.fxml"));
    Parent anchorPane = fxmlLoader.load();
    
    controller = fxmlLoader.getController();
    controller.doSomeThing("myText");
    ...
    

    And in the Controller define a public function.

    MyController :

    public void doSomeThing(String myText) {
        myTextField.setText(myText);
    }