Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Build a JavaFX Application Design a Better App The Controller

Juneau Lim
Juneau Lim
13,362 Points

"firstName" is marked as red, InvocationTargetException thrown

<!--sample.fxml-->
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.text.Text?>
<?import javafx.scene.control.TextField?>
<GridPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
    <Text text="Sup"
          GridPane.rowIndex="0"
          GridPane.columnSpan="2"
          GridPane.halignment="CENTER"/>

    <Label text="First Name:"
           GridPane.rowIndex="1"
           GridPane.columnIndex="0" />

    <TextField fx:id="firstName"     
            GridPane.rowIndex="1"
            GridPane.columnIndex="1"/>
            <!--Cannot set javafx.scene.control.TextField to field 'firstName'-->

    <Button text="Say Sup"
            onAction="#handleSaySup"
            GridPane.rowIndex="2"
            GridPane.columnIndex="1"
            GridPane.halignment="RIGHT"/>
</GridPane>
// Controller.java
package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;

import java.awt.*;

public class Controller {

    @FXML private TextField firstName;

    public void handleSaySup(ActionEvent actionEvent) {
        System.out.printf("Sup %s! %n", firstName.getText());
    }
}

Not so sure where was the mistake. :-( It was ok until I added handleSaySup method

1 Answer

Hey there,

I took a look at your code and I think the issue here is a missing import statement. if you add the following line on your controller I think the issue should resolve itself.

import javafx.scene.control.TextField;

Part of what is causing the confusion here is that you have a blanket import on java.awt which ALSO has a text field. This is why the IDE isn't reporting an issue with it in the controller.

Juneau Lim
Juneau Lim
13,362 Points

How silly I am. Thanks a lot!

No problem at all. It is a really easy mistake to make and not entirely obvious at first glance.