0

I'm creating my first GUI application. I have a class called User and I have an instance of that class called newUser and I created and initialized it in newGameController.java (User newUser = new User(username); but I would like to use it in mainScreenController as well but I get the error cannot resolve symbol 'newUser'

I don't really understand how MVC works and I believe I have a major design flaw, can someone help me on how to make it so I can use one object in two controllers or alternatives? Here is my code below.

User.java

package sample.model;

public class User {
    private String name;
    private double money;
    public User(String name) {
        this.name = name;
        money = 20000;
    }
    public String getName() {
        return name;
    }
}

newGameController.java

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import sample.model.User;

import java.io.IOException;


public class newGameController {

    @FXML
    private Label mainmessage;
    @FXML
    private TextField userid;
    @FXML
    private Button submit;

    @FXML
    private void handleButtonAction(ActionEvent event) throws IOException {
        try {
            Stage stage;
            Parent root;
            String username = userid.getText();
            User newUser = new User(username);

            stage = (Stage) submit.getScene().getWindow();
            root = FXMLLoader.load(getClass().getResource("mainscreen.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

        }
        catch(NullPointerException e)
        {

        }

    }

mainscreenController.java

package sample;


import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

import java.net.URL;
import java.util.ResourceBundle;

public class mainscreenController implements Initializable {
    @FXML
    private Label name;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        name.setText(newUser.getName());
    }

}

1 Answers1

0

In you mainscreenController class:-

name.setText(newUser.getName());

In the above line you referring to newUser but this class is not aware of type of newUser. Since you have not declare this variable in this class.

Add the import sample.model.User statement at the top and define the type of newUser object.
Relation of newUser object initialized in controller and used mainscreenController doesn't look related to each other.

Even if you declare the type of newUser in mainscreenController i.e. User newUser;, it will throw NullPointerException. As I don't see it getting initialized in mainscreenController.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45