NullPointerException when calling method from another class

kristoffer sylte dahl :

I am having a problem with a text-based game I'm making. I am fairly new to java and drawing GUI's in java, so I suspect my overall structure might be the root of the problem. So bear with me;

My main class, instantiates a new Gamelobby().

class untitledRPG {

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

The GameLobby instantiates a MainMenu().

class GameLobby {

    {
    mainMenu = new MainMenu();
    }
}

The MainMenu() looks like this, and instatiates a GameWindow() if the player chooses the 'New Game'-button, as well as an Intro(), which is where the game-text will come from.

public class MainMenu {    

    private String newGame;
    private String loadGame;
    private String settings;
    private JFrame frame = new JFrame("UntitledRPG™ Main Menu");

    public MainMenu() {
        newGame = "New Game";
        loadGame = "Load Game";
        settings = "Settings";
        buildWindow(frame);
    }

    private void buildWindow(JFrame frame)
    {
        // Main build
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(400, 220);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);

        // Draw layout with grid
        // Look into GridBagLayout if this proves insufficient
        frame.setLayout(new GridLayout(3,1));
        JPanel field1 = new JPanel();
        JPanel field2 = new JPanel(new GridLayout(1, 3));
        JPanel field21 = new JPanel();
        JPanel field22 = new JPanel();
        JPanel field23 = new JPanel();
        field2.add(field21);
        field2.add(field22);
        field2.add(field23);
        JPanel field3 = new JPanel();

        // Instantiate objects
        JLabel welcomeTextLabel = new JLabel();
        JLabel gameDescLabel = new JLabel();
        JButton newGameBtn = selectGameTypeBtn(newGame);
        JButton loadGameBtn = selectGameTypeBtn(loadGame);
        JButton settingsBtn = selectGameTypeBtn(settings);

        // Set values. Can be integrated to the instantiation 
        String welcomeText = "Welcome to the Untitled RPG!";
        String gameDesc = "<html>Press 'New Game' to start your adventure,<br /> or 'Load Game' to continue an existing one!</html> ";
        settingsBtn.setText("Settings");
        welcomeTextLabel.setText(welcomeText);
        gameDescLabel.setText(gameDesc);

        //Add objects to panels
        field1.add(welcomeTextLabel);
        field21.add(newGameBtn);
        field22.add(loadGameBtn);
        field23.add(settingsBtn);
        field3.add(gameDescLabel);

        // Add panels to grid
        frame.add(field1);
        frame.add(field2);
        frame.add(field3);

        frame.setVisible(true);
    }

    private JButton selectGameTypeBtn(String btnName) {
        JButton returned = new JButton(btnName);
        returned.addActionListener(e -> {
            JButton source = (JButton)e.getSource();
            if (source.getText().equalsIgnoreCase(newGame)) {
                new GameWindow().openGameWindow();
                new Intro();
                frame.dispose();
            }
            if (source.getText().equalsIgnoreCase(loadGame)) {
                popUp popUp = new popUp();
                popUp.popUpWindow("You have no saves to load!", "Error!");

            }
            if (source.getText().equalsIgnoreCase(settings)) {
                popUp popUp = new popUp();
                popUp.popUpWindow("We haven'made any settings yet!", "Error!");
            }
        });
        return returned;
    }
}

GameWindow() looks like this:

public class GameWindow {

private JTextArea sideBarArea;
private JTextArea gameArea;
private JTextArea inputAreaTextArea;
private JTextField inputAreaTextField;
private GridBagConstraints c;

 public GameWindow() {
    c = new GridBagConstraints();
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    int hGap = 5;
    int vGap = 5;
    c.insets = new Insets(hGap, vGap, hGap, vGap);
}

public void openGameWindow() {
    JFrame frame = new JFrame("UntitledRPG™");
    buildGameWindow(frame);
}

private void buildGameWindow(JFrame frame) {

    /* GameWindow build info
    GameWindow consists of:
    - gameArea, a JTextField where the output from the game will be printed.
    - sideBarArea, TODO
    - inputArea, a JPanel where the player enters commands and views them in a log
     */

    // Main build
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(700, 600);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    // Set areas
    gameArea = new JTextArea(5, 10);
    sideBarArea = new JTextArea(5, 10);
    JPanel inputArea = new JPanel(new GridBagLayout());

    // GAME AREA
    gameArea.setEditable(false);
    gameArea.setCaretPosition(gameArea.getDocument().getLength());
    JScrollPane gameAreaScrollPane = new JScrollPane(gameArea);

    //SIDEBAR AREA
    sideBarArea.setEditable(false);

    // INPUT AREA.
    // Set textArea and add it to scrollpane, which is then added to the layout
    inputAreaTextArea = new JTextArea(10,20);
    inputAreaTextArea.setEditable(false);
    inputAreaTextArea.setCaretPosition(inputAreaTextArea.getDocument().getLength());

    // Message in the inputAreaTextArea to user.
    String welcomeMsg= "This is your command log. Your commands will be printed here.";
    printToLog(welcomeMsg);
    JScrollPane textAreaScrollPane = new JScrollPane(inputAreaTextArea);

    // (addComp) method for placing elements in gridBagLayout.
    addComp(inputArea, textAreaScrollPane, 0, 1, 1, 1, GridBagConstraints.BOTH, 2, 2);

    // Label with user instruction on using the inputAreaTextField
    JLabel inputAreaLabel = new JLabel("Enter commands below.");
    addComp(inputArea, inputAreaLabel, 0,2, 1, 1, GridBagConstraints.BOTH, 0.2,0.2);

    // Set jTextfield and add it to layout
    inputAreaTextField = new JTextField();
    inputAreaTextField.setText("Start your adventure!"); // Placeholder, see method below
    addComp(inputArea, inputAreaTextField, 0, 3, 2, 2, GridBagConstraints.BOTH, 0.2, 0.2);

    // Listener for enter-click
    inputAreaTextField.addActionListener((e -> {
        if(inputAreaTextField.getText().length() > 0) {
            printToLog(inputAreaTextField.getText());
            inputAreaTextField.setText("");
        }
    }));

    // Method for the placeholder text. Show up one time before textField is in focus
    inputAreaTextField.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            JTextField source = (JTextField)e.getComponent();
            source.setText("");
            source.removeFocusListener(this);
        }
    });

    // ASSEMBLY
    // Set vertical splitpane. Second layer
    JSplitPane vertSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, gameArea, sideBarArea);
    vertSplitPane.setDividerLocation(500);
    vertSplitPane.setDividerSize(10);
    vertSplitPane.setEnabled(false);

    // Set horizontal split. Top layer
    JSplitPane horiSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, vertSplitPane, inputArea);
    vertSplitPane.setOneTouchExpandable(false);
    horiSplitPane.setDividerLocation(400);
    horiSplitPane.setDividerSize(5);
    horiSplitPane.setEnabled(false);

    frame.add(horiSplitPane);
}

// Easier implementation of constraints for gridBagLayout
private void addComp(JPanel panel, JComponent comp
                        , int x, int y, int gWidth
                            , int gHeight, int fill
                                , double weightx, double weighty) {
    c.gridx = x;
    c.gridy = y;
    c.gridwidth = gWidth;
    c.gridheight = gHeight;
    c.fill = fill;
    c.weightx = weightx;
    c.weighty = weighty;

    panel.add(comp, c);
}

// Prints  player command to inputAreaTextField (log)
public void printToLog(String text) {
    inputAreaTextArea.append(">" + text + "\n");
    inputAreaTextArea.setCaretPosition(inputAreaTextArea.getDocument().getLength());
}

public void printToGameArea(String text) {
     gameArea.append(">" + text + "\n");
     gameArea.setCaretPosition(gameArea.getDocument().getLength());
}
}

Intro() looks like this:

public class Intro {

Print print;
Player player;


public Intro()
{
    player = new Player();
    print = new Print();
    player = charCreation();
}

private Player charCreation() {
    GameWindow gameWindow = new GameWindow();
    gameWindow.printToGameArea("Wake up");
    player.setAge(21);
    player.setName("Kris");
    player.setGender("m");
    return player;
}
}

But when I run this, I get this nullPointerException:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI.GameWindow.printToGameArea(GameWindow.java:138)
at Gameplay.Intro.charCreation(Intro.java:21)
at Gameplay.Intro.<init>(Intro.java:16)
at GUI.MainMenu.lambda$selectGameTypeBtn$0(MainMenu.java:78)

I am having some trouble wrapping my head around what is causing this, and how I might improve the overall structure.

Thanks in advance for any help, and please let me know if my question does not meet the SO-standards. I am new to this as well.

Shahid :

You need to call openGameWindow that eventually call buildGameWindow before calling printToGameArea to initialize the component.

private Player charCreation() {
    GameWindow gameWindow = new GameWindow();
    gameWindow.openGameWindow();
    gameWindow.printToGameArea("Wake up");
    player.setAge(21);
    player.setName("Kris");
    player.setGender("m");
    return player;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Javascript

Calling a method from another method in the same class

From Java

Calling method of Another class from run() method

From Java

java calling a method from another class

From Java

Calling service method from another service class

From Java

Java cannot find symbol when calling a method from another class

From Dev

calling render method from another class

From Dev

NullPointerException for calling another class array

From Dev

Mockito : java.lang.NullPointerException when calling method from mocked Class

From Dev

Calling a method from another class that removes views

From Dev

NullPointerException when calling a method from a different class

From Dev

Calling a class method from another class method in Python 2.7

From Dev

Calling a class from another class with main method

From Dev

Calling method from another class in onPostExecute causing nullPointerException

From Dev

Calling a method from another class in broadcast receiver

From Dev

NullPointerException when calling a Fragment method from Activity?

From Dev

Calling method from another class unsuccessful

From Dev

Calling StartActivity(intent) method from another class

From Dev

Calling a method from inside of another class

From Dev

`this` is undefined when calling method from another context

From Dev

Python: Calling a decorator method from another class

From Dev

Calling a method of the MainActivity from another class?

From Dev

calling a boolean method from another class

From Dev

Having trouble calling a method from another class

From Dev

calling method in mainactivity from another class in android

From Dev

Calling a method from one class in another class

From Dev

JGroups RpcDispatcher calling method from another class

From Dev

Syntax Error in Calling a method from another class

From Dev

python, calling a method from another class

From Dev

SpringBoot @Autowired NullPointerException when calling method from service class

Related Related

  1. 1

    Calling a method from another method in the same class

  2. 2

    Calling method of Another class from run() method

  3. 3

    java calling a method from another class

  4. 4

    Calling service method from another service class

  5. 5

    Java cannot find symbol when calling a method from another class

  6. 6

    calling render method from another class

  7. 7

    NullPointerException for calling another class array

  8. 8

    Mockito : java.lang.NullPointerException when calling method from mocked Class

  9. 9

    Calling a method from another class that removes views

  10. 10

    NullPointerException when calling a method from a different class

  11. 11

    Calling a class method from another class method in Python 2.7

  12. 12

    Calling a class from another class with main method

  13. 13

    Calling method from another class in onPostExecute causing nullPointerException

  14. 14

    Calling a method from another class in broadcast receiver

  15. 15

    NullPointerException when calling a Fragment method from Activity?

  16. 16

    Calling method from another class unsuccessful

  17. 17

    Calling StartActivity(intent) method from another class

  18. 18

    Calling a method from inside of another class

  19. 19

    `this` is undefined when calling method from another context

  20. 20

    Python: Calling a decorator method from another class

  21. 21

    Calling a method of the MainActivity from another class?

  22. 22

    calling a boolean method from another class

  23. 23

    Having trouble calling a method from another class

  24. 24

    calling method in mainactivity from another class in android

  25. 25

    Calling a method from one class in another class

  26. 26

    JGroups RpcDispatcher calling method from another class

  27. 27

    Syntax Error in Calling a method from another class

  28. 28

    python, calling a method from another class

  29. 29

    SpringBoot @Autowired NullPointerException when calling method from service class

HotTag

Archive