Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.