使用loop(for)在JPanel中添加JButton?

时间:2013-06-02 15:20:14

标签: java swing loops jpanel jbutton

我正在尝试制作战舰游戏,并且在使用循环时我没有成功在JButton中添加JPanel。我可以逐个添加,但不能在for循环中添加。

只有在编译时我才会收到任何错误;

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

以下是代码:

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 个答案:

答案 0 :(得分:2)

您尚未初始化按钮数组,因此以下行会抛出异常:

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

您的代码缺少以下内容:

bouton = new JButton[16][8];