0

I'm pretty new to Java FX and fxml templates, I know that to access to an object's methods you need to use setOnAction and declare a specific method into the controller class. Is there a way to access to its methods from code without using setOnAction?

Example what I want to do:

FXML Document

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="package.Controller">
   <children>
      <Label fx:id="myLabel" text="Label" />
   </children>
</VBox>

Controller class

    public class Controller {
    @FXML
    Label myLabel;

    public Controller() {
        this.mylabel = new Label();

        //some code here

        myLabel.setText("modified text 0");

        //some code here

        myLabel.setText("modified text 1");
    }
}

Is that possible in some way by not using setOnAction custom method?

Steve Wolf
  • 123
  • 2
  • 11
  • Possible duplicate of [In JavaFX, is binding an alternative to action-listener?](https://stackoverflow.com/questions/19610581/in-javafx-is-binding-an-alternative-to-action-listener) – Amogh Aug 29 '17 at 18:35
  • Can you edit your question to include an example that shows what you are trying to do? Can't you just inject the control into the controller using [`@FXML`](http://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html#fxml_annotation) and call methods on it there as needed? – James_D Aug 29 '17 at 18:36
  • Do you mean accessing the controller instance, for a loaded FXML file? – jrtapsell Aug 29 '17 at 20:12
  • @James_D Added example – Steve Wolf Aug 29 '17 at 21:22
  • 1. Don't create a new label: you presumably want to use the label created in the FXML file, not one you just create on the fly. 2. The `@FXML`-annotated fields won't have been initialized when the constructor is invoked (how could they?). Call the methods in the `initialize()` method instead. See https://stackoverflow.com/questions/34785417/javafx-fxml-controller-constructor-vs-initialize-method (Also look at the [documentation](http://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html#fxml_annotation).) – James_D Aug 29 '17 at 21:29
  • If you want to access to your methods ,implements initializable interface and call your methods from initialize() method. – Menai Ala Eddine - Aladdin Aug 29 '17 at 22:20
  • 1
    @MenaiAlaEddine It has not been necessary to implement `Initializable` since JavaFX version 2.1. – James_D Aug 29 '17 at 22:42
  • @James_D if i try `initialize()` method I get NullPointerException – Steve Wolf Aug 30 '17 at 05:49
  • Then something else is wrong somewhere. – James_D Aug 30 '17 at 09:03

0 Answers0