1

I'm trying to make a battleship game and I don't succeed adding JButtons in a JPanel while using a loop. I can add it one by one, but not in a for loop.

I don't get any error, only when compilation;

"Exception in thread "main" java.lang.NullPointerException
at Allo.<init>(Allo.java:38)
at Allo.main(Allo.java:55)"

Here's the code:

import javax.swing.JFrame;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import java.awt.Color;
import javax.swing.JButton;  

public class Allo {    

  JFrame fenetre = new JFrame();
  static JButton[][] bouton; 

  public Allo(int width, int height) {    
     fenetre.setSize(800, 500);
     fenetre.setResizable(false);
     SpringLayout springLayout = new SpringLayout();
     fenetre.getContentPane().setLayout(springLayout);    
     JPanel panel = new JPanel();
     panel.setBackground(Color.DARK_GRAY);    
     fenetre.getContentPane().add(panel);
     SpringLayout sl_panel = new SpringLayout();
     panel.setLayout(sl_panel);
     for (int r = 0; r < 16; r++)
     {
        for (int c = 0; c < 8; c++)
        {    
           bouton[r][c] = new JButton("("+r+","+c+")");   
           panel.add(bouton[r][c]);    
           //fenetre.getContentPane().add(bouton[r][c]);
        }
     }
     fenetre.setVisible(true);
   }    

    public static void main(String[] args) {
    // TODO Auto-generated method stub
       new Allo(16,8);   
   }
}

1 Answer 1

2

You haven't initialized your array of buttons, so the following line throws the exception:

bouton[r][c] = new JButton("("+r+","+c+")");  

Your code lacks the following line:

bouton = new JButton[16][8];
Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe, unbelievable kindness be your majesty +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.