0

So if i try to use a button from the fxml using the @FXML i get a nullpointer exception or nothing happens. I'm new with javafx so go easy on me, but no matter what i try it doesnt seem to work...

In the fxml file i have a button created in scenebuilder with fx:id="companies" - this all works fine and is definitely implemented properly.

In my java main file this is the code:

package sample;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.File;


public class Main extends Application {

    @FXML private Button companies;

    @Override
    public void start(Stage primaryStage) throws Exception{

        companies.setOnAction(event -> {
           companies.setText("new value");
             });

        File file = new File("/users/Joss/Documents/continents.gif");

        Image image = new Image(file.toURI().toString());
        ImageView imageview = new ImageView(image);

        BorderPane pane = FXMLLoader.load(Main.class.getResource("sample.fxml"));
        //mainPane.setCenter(imageview);

        Scene scene = new Scene(pane, 1000, 800);
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

and this is the error: Caused by: java.lang.NullPointerException at sample.Main.start(Main.java:24)

  • You are trying to access the button before you even load the FXML file, so you have no hope that it is initialized at that point. However, the full story is more complex, as explained in the linked question. Take-home story: use a different class for the controller. – James_D Jan 19 '16 at 18:57
  • Ah i see, thank you very much... –  Jan 19 '16 at 19:01

0 Answers0