Archie
Archie

Reputation: 13

Java- JPanel design problems

UPDATE: NVM IM AN IDIOT PASSING A NULL

ummm so I recently learned about panels and I'm trying to redesign the start menu of a tictactoe project, nothing major.

This is my dream:

enter image description here

This is my current code:

public static void modeGUI () {

    //MAIN JFRAME GUI
    JFrame gui = new JFrame("TicTacToe");
    gui.setVisible(true);
    gui.setSize(600, 200);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //MAIN PANEL
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(3, 1));
    gui.add(mainPanel);

    //QUESTION PANEL
    JPanel questionPanel = new JPanel();
    questionPanel.setLayout(new FlowLayout());
    JLabel q1 = new JLabel("Please select your mode");
    q1.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    questionPanel.add(q1);
    mainPanel.add(questionPanel);

    //MODE PANEL
    JPanel  modePanel = new JPanel();
    modePanel.setLayout(new GridLayout());
    JButton[] modeButtons = new JButton[3];
    modeButtons[0].setText("First turn");
    modeButtons[1].setText("Second turn");
    modeButtons[2].setText("P vs. P");
    for (JButton modeButton : modeButtons) {
        modeButton.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        modeButton.addActionListener(new Response());
        modePanel.add(modeButton);
    }
    mainPanel.add(modePanel);

    //OPTION PANEL
    JPanel optionsPanel = new JPanel();
    optionsPanel.setLayout(new FlowLayout());
    mainPanel.add(optionsPanel);
}

However when I attempt to run it it gives an error at line 30, which correlates to this line: modeButtons[0].setText("First turn");. Can anyone help see what's wrong?

This is the error btw:

Exception in thread "main" java.lang.NullPointerException at Ttt.modeGUI(Ttt.java:30) at Ttt.main(Ttt.java:7)

Upvotes: 0

Views: 49

Answers (1)

AlterV
AlterV

Reputation: 301

The array of buttons is empty.

JButton[] modeButtons = new JButton[3];

This line creates an array of JButtons, but each element is by default set to null (as with the creation of all arrays).

So when you try this

modeButtons[0].setText("First turn");

A NullPointerException is thrown since modeButtons[0] is null. You have to explicitly define each button before you can begin assigning their values.

Upvotes: 1

Related Questions