0

How can I update the text of the label currentPlayerFileLabel from the if statement, so it gets the path from the file (if it is there); otherwise gets the default String?

Code as of now:

package sample;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import sample.controllers.Util;
import sample.model.Config;

import java.io.File;
import java.net.URL;
import java.security.spec.ECField;
import java.util.ResourceBundle;

public class Main extends Application implements Initializable {
    private Stage primaryStage = new Stage();
    private BorderPane rootLayout;
    private AnchorPane anchorPanePlayer;
    private BorderPane borderPaneGame;
    private Config config = new Config();
    private StringProperty isPlayerFileThere = new SimpleStringProperty("No playerfile was fund! Add new one in \"File\"");

    @FXML
    private Button playersButton;
    @FXML
    private Button gamesButton;
    @FXML
    private Button quitButton;

    @FXML
    private Label currentPlayerFileLabel = new Label();

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("Main window");

        initLayout();
        initConfig();

    }
    //----------- MY QUESTION IS ABOUT THIS METHODE -------------------------------
    public void initConfig() {
        File configFile = new File(System.getProperty("user.dir") + "/Config/config.txt");
        if (configFile.exists()) { // Returns true as of now, so the "true" statement of the if statement will be called
            config = Util.initConfigFile();
            isPlayerFileThere.setValue(config.getPlayerFileLocation().toString());
            currentPlayerFileLabel.setText(getIsPlayerFileThere());
        } else {
            currentPlayerFileLabel.setText(getIsPlayerFileThere());

        }
    }
    //----------- MY QUESTION IS ABOUT THIS METHODE -------------------------------

    public void initLayout() {
        try {
            //Load root layout from fxml
            FXMLLoader loader = new FXMLLoader(); //Makes a new FXMLLoader
            loader.setLocation(Main.class.getResource("view/mainView.fxml")); //sets the location of the main fxml file
            rootLayout = loader.load(); //Loads the anchorpane from the loader, (AnchorPane) is redundent.
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    public void initPlayerLayout() {
        try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class.getResource("view/playerEdit.fxml")); // Gets the new layout.
            anchorPanePlayer = loader.load(); //Loades the new layout
            Scene playerScene = new Scene(anchorPanePlayer); //adds a new scene with the loaded layout
            Stage prevStage = (Stage) playersButton.getScene().getWindow(); //Get the stage from where we come from.
            prevStage.close(); //Closes the prev stage
            primaryStage.setScene(playerScene); //Sets new stage with the new layout
            primaryStage.show(); //Shows new stage

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initGameLayout() {
        try {

            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class.getResource("view/editGame.fxml"));
            borderPaneGame = loader.load();
            Scene gameScene = new Scene(borderPaneGame);
            Stage prevStage = (Stage) gamesButton.getScene().getWindow();
            prevStage.close();
            primaryStage.setScene(gameScene);
            primaryStage.show();

        } catch (Exception e) {
            e.getStackTrace();

        }
    }

    public void quitProgram() {
        Stage stageToQuit = (Stage) quitButton.getScene().getWindow();
        stageToQuit.close();
    }

    public Stage getPrimaryStage() {
        return primaryStage;
    }

    public AnchorPane getBorderPanePlayer() {
        return anchorPanePlayer;
    }

    public Config getConfig() {
        return config;
    }

    public void addPlayerFile() {
        config.setPlayerFileLocation(Util.addPlayerFile());
    }

    public String getIsPlayerFileThere() {
        return isPlayerFileThere.get();
    }

    public StringProperty isPlayerFileThereProperty() {
        return isPlayerFileThere;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        currentPlayerFileLabel.setText(getIsPlayerFileThere());
    }

    public static void main(String[] args) {

        launch(args);
    }


}

FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.Text?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Main">
   <bottom>
      <HBox prefHeight="100.0" prefWidth="200.0" spacing="40.0" BorderPane.alignment="CENTER">
         <children>
            <Region HBox.hgrow="ALWAYS" />
            <Button fx:id="playersButton" mnemonicParsing="false" onAction="#initPlayerLayout" text="Players" />
            <Button fx:id="gamesButton" layoutX="10.0" layoutY="10.0" mnemonicParsing="false" onAction="#initGameLayout" text="Games" />
            <Button fx:id="quitButton" layoutX="69.0" layoutY="10.0" mnemonicParsing="false" onAction="#quitProgram" text="Quit" />
            <Region layoutX="10.0" layoutY="10.0" HBox.hgrow="ALWAYS" />
         </children>
      </HBox>
   </bottom>
   <top>
      <MenuBar BorderPane.alignment="CENTER">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
              <MenuItem fx:id="addPlayerFileMenu" mnemonicParsing="false" onAction="#addPlayerFile" text="Add new player file" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Edit">
            <items>
              <MenuItem mnemonicParsing="false" text="Delete" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
   </top>
   <center>
      <HBox prefHeight="100.0" prefWidth="200.0" BorderPane.alignment="CENTER_RIGHT">
         <children>
            <VBox alignment="CENTER" HBox.hgrow="ALWAYS">
               <children>
                  <Label text="Welcom to the main menu!" />
                  <Label fx:id="currentPlayerFileLabel" text="Label" />
               </children>
            </VBox>
         </children>
      </HBox>
   </center>
</BorderPane>

UPDATE Have now worked out how to do it, with the help from the comments on this question. To others with the same problem, here is the code that I got to work:

Main class:

package sample;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import sample.controllers.MainController;
import sample.controllers.Util;
import sample.model.Config;

import java.io.File;
import java.net.URL;
import java.security.spec.ECField;
import java.util.ResourceBundle;

public class Main extends Application {
    MainController mainController = new MainController();
    Stage primaryStage;

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

        this.primaryStage = primaryStage;
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("view/mainView.fxml"));
        loader.setController(mainController);
        Parent root = loader.load();
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public Stage getPrimaryStage() {
        return primaryStage;
    }

    public static void main(String[] args) {

        launch(args);
    }


}

The controller for the layout of the main window and the part that is interesting:

 ...
    private Stage primaryStage = new Stage();
    private AnchorPane anchorPanePlayer;
    private BorderPane borderPaneGame;
    private Config config = new Config();
    private StringProperty isPlayerFileThere = new SimpleStringProperty("No playerfile was fund! Add new one in \"File\"");

    @FXML
    private Button playersButton;
    @FXML
    private Button gamesButton;
    @FXML
    private Button quitButton;

    @FXML
    private Label currentPlayerFileLabel;

 ...     
    @Override
            public void initialize(URL location, ResourceBundle resources) {
                File configFile = new File(System.getProperty("user.dir") + "/Config/config.txt");
                if (configFile.exists()) { // Returns true as of now, so the "true" statement of the if statement will be called
                    config = Util.initConfigFile();
                    isPlayerFileThere.setValue(config.getPlayerFileLocation().toString());
                    currentPlayerFileLabel.setText(getIsPlayerFileThere());
                } else {
                    currentPlayerFileLabel.setText(getIsPlayerFileThere());

                }
            }
  ...

The FXML line that has been updated:

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" >
Lasse
  • 597
  • 2
  • 10
  • 33
  • 1
    So what is the question? Also - it appears as if the label is never added to the scene graph. – Itai Dec 27 '15 at 12:22
  • The question is as i wrote: How can i update the text of the label oppon a switch statement. The label is from the fxml file. – Lasse Dec 27 '15 at 12:44
  • 1
    Why are you using your `Application` class as the controller class? – James_D Dec 27 '15 at 14:09
  • I don't really know.. I'm trying to learn JavaFX and it was natual for me to use the main as the controller for the mainLayout.. I can figure out that this is not the smartest thing ? – Lasse Dec 27 '15 at 14:12
  • 1
    Use a separate controller class and make your initConfig() method the initialize() method. – James_D Dec 27 '15 at 14:45

1 Answers1

1

You are overriding the label, so you do no longer use the instance that is defined in your FXML:

@FXML
private Label currentPlayerFileLabel = new Label();

Remove the assignment to a new label.

hotzst
  • 7,238
  • 9
  • 41
  • 64
  • Well.. then I get a NullPointerException.. :/ – Lasse Dec 27 '15 at 13:48
  • 1
    Then it seems that `currentPlayerFileLabel` is not mapped from the FXML. Can you add the FXML to your question, that might actually help. – hotzst Dec 27 '15 at 13:50
  • I have added it to the main question :) – Lasse Dec 27 '15 at 14:06
  • 1
    The reason you are getting `NullPointerException` is that you try to change the text before the label is created. Move the `initConfig` call to the `initialize` method - there all `FXML`-annotated variables should be injected. And as @James_D said - you really shouldn't use your application class as a controller. – Itai Dec 27 '15 at 14:29
  • 1
    More precisely, you have two instances of the class. The instance in which you are trying to set the text is not the instance in which the label is injected. – James_D Dec 27 '15 at 14:46