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

Sam Gerstner
Sam Gerstner
5,258 Points

Getting a NullPointerException

I keep getting a NullPointerException on my Controller class. My code will compile and open the new window then I get the error when I click to Say Sup! button. Here is my Controller class.

package sample;

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

import java.awt.*;

public class Controller {

@FXML private TextField fName;

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

}

2 Answers

Tamara Lavalli
Tamara Lavalli
5,707 Points

Hey, Sam Gerstner! It looks like, you get the nullpointer exception because you call ".getText()" on fname before assigning a value to it.

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,795 Points

Sam Gerstner

Also check the id for TextField on your fmxl file, its value should be fx:id="fName" - same letter case as the Controller's TextField value.

I also note you have imported awt - Abstract Window Toolkit - on your imports.

You should have these imports instead:

import javafx.event.ActionEvent; import java.fxml.FXML; import javafx.scene.control.TextField;

Cheers