Search code examples
javaswingloopsjpaneljbutton

Adding JButton in JPanel using loop (for)?


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);   
   }
}

Solution

  • 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];