1

I have a custom JavaFX component extending the Tab class:

public class MyTab extends Tab implements Initializable {
  @FXML private TextField myInput;
  private final MyDTO dto;

  public MyTab(MyDTO dto) { 
    super(); 
    this.dto = dto; 

    final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/my-tab.xml"));
    fxmlLoader.setResources(MSG.getResourceBundle());
    fxmlLoader.setRoot(this);
    fxmlLoader.setController(this);
    try {
        fxmlLoader.load();
    }
    catch (IOException exception) {
        throw new RuntimeException(exception);
    }
  }

  @Override
  public void initialize(URL url, ResourceBundle res) {
    setText("My Tab");
    myInput.setText(dto.getValue());      // !!!
  }
}

With the FXML:

<fx:root type="javafx.scene.control.Tab" xmlns:fx="http://javafx.com/fxml">
<content>
  <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
    <children>
      <Label id="myLabel" layoutX="14.0" layoutY="14.0" text="Text:" />
      <TextField id="myInput" layoutX="162.0" layoutY="10.0" prefHeight="25.0" prefWidth="300.0" />
    </children>
  </AnchorPane>
</content>
</fx:root>

I need to create this objects (custom tabs) dynamically from the java code:

final MyTab myTab = new MyTab(new MyDTO(...));
tabPane.getTabs().add(myTab);

When I use it like this, the @FXML binding doesn't work and the line

myInput.setText(dto.getValue());

throws NullPointerException. When the line with the setting of the text from the code is commented, the input is showned, so the problem is only in the binding.

I am using JavaFX 2 for Java 1.7

Thank you for any idea!

2
  • Your code as you posted it doesn't really make sense, because the FXML <MyTab> element would invoke a zero-argument constructor on MyTab, which doesn't exist. That said, it looks like it should work. Can you create and post an MCVE that produces the null pointer exception? Commented Aug 7, 2015 at 12:45
  • You're right, I put the contrustructor with the parameter as I left the pure FXML solution, I edited the question. Commented Aug 7, 2015 at 12:48

1 Answer 1

1

Solution is very easy, I just overlooked the mistake in the FXML code:

Should be

<TextField fx:id="myInput" ...

instead of

<TextField id="myInput" ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.