Search code examples
javajavafxfxml

FXML injection in javafx, how can it turn null suddenly?


when i debug the program hiddenMenu has a value when it reaches the initialize method. However, when i later create a Large Circle and add a clickevent on it, i want the hiddenMenu to be invisible.

When i try hiddenMenu.setVisible(false) i get a nullpointerexception. I know i haven't changed anything on the way. Am i forgetting or missing something?

i have tried hiddenMenu.setVisible(false); without success.

here is the code:

public class MainWindow extends Application implements Initializable {

@FXML
private AnchorPane root;

@FXML
private ComboBox<String> chooseFigureComboBox;

@FXML
private Button btnCreate;

@FXML
private HBox hiddenMenu;

@FXML
private ColorPicker cp;

@FXML
private Label lblColor;

@FXML
private Label lblSize;

@FXML
private Slider sli;

private Shape selected;
private List<Node> selectionList = new LinkedList<>();
private static MainWindow mainWindow;
private FigureHandler figureHandler;
private ObservableList<String> figures;
private ArrayList<Circle>circles;

@Override
public void start(Stage scene) throws Exception{
    MainWindow.mainWindow = this;
    figureHandler = FigureHandler.getInstance();
    figureHandler.setMainWindow(mainWindow);
    root = FXMLLoader.load(getClass().getResource("../grafik/mainWindow.fxml"));

    scene.setTitle("Hello World");
    scene.setScene(new Scene(root, 800, 600));
    scene.show();
}

public void addLargeCircle(){

    Circle circle = new Circle();
    circle.setRadius(100);
    circle.setFill(Color.RED);
    circle.addEventHandler(MouseEvent.MOUSE_CLICKED,e->{
        System.out.println("Ett klick skedde på cirkeln!");

        hiddenMenu.setVisible(false);

    });

    circle.addEventHandler(MouseEvent.MOUSE_DRAGGED,e->{
        moveCircle(e,circle);
    });

    root.getChildren().add(circle);
    //circles.add(circle);
    //figureHandler.addCircleToList(circle);
}

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {


    figures = FXCollections.observableArrayList("small Circle","medium circle","large Circle");
    chooseFigureComboBox.setItems(figures);
    circles = new ArrayList<>();

    cp.setValue(Color.RED);
    cp.setOnAction(e->{
        System.out.println("Changed color");
    });
}

//skipping some methods that has nothing to do with the problem.

Expected it to not show, what i get is a NPE.


Solution

  • The main problem was that I used the following code:

    root = FXMLLoader.load(getClass().getResource("../grafik/mainWindow.fxml"));
    

    instead of this code:

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/grafik/mainWindow.fxml"));
    mainWindowRoot = loader.load();
    

    Once I fixed that, everything started to work! Thanks for help and feedback, I have corrected to appropriate solutions for your remarks!