Ajuda não adicciona o array de botões ao Jframe

1 resposta
Z

boas

Eu gostaria muito que me ajudassem num erro que não entendo.

Exception in thread “main” java.lang.NullPointerException

at java.awt.Container.addImpl(Container.java:1041)

at java.awt.Container.add(Container.java:365)

at jogo_xadrez.Tabuleiro.(Tabuleiro.java:46)

at jogo_xadrez.Main.main(Main.java:19)

Java Result: 1
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jogo_xadrez;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 
 */
public class Tabuleiro extends JFrame {
    private JButton[][] tab;
    private int linha;
    private int coluna;
    private JPanel painel;
    private JButton botao;

    

    Tabuleiro(int linha, int coluna){
        setTitle("Jogo de Xadrez");
        setSize(800,800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.painel = new JPanel();
        this.add(this.painel);

        this.linha = linha;
        this.coluna = coluna;
        this.tab = new JButton[linha][coluna];
        for (int i = 0; i < linha; i++) {
            for (int j = 0; j < coluna; j++) {
                
                    this.tab[i][j] = new JButton("");
                    this.tab[i][j].setVisible(true);
                
            }
        }

        for (int i = 0; i < linha; i++) {
            for (int j = 0; j < coluna; j++) {
                this.painel.add(this.tab[i][j]);
            }
        }
    }
package jogo_xadrez;

/**
 *
 * @author
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Tabuleiro t = new Tabuleiro(8,8);
        t.setVisible(true);

    }

}

Desde já agradeço.

1 Resposta

R

Testei seu código aqui e executou sem problemas. Fiz algumas modificações:

public class Tabuleiro extends JFrame {
  private JButton[][] tab;
  private int linhas;
  private int colunas;
  private JPanel painel;
  private JButton botao;

  Tabuleiro(int linhas, int colunas) {
    setTitle("Jogo de Xadrez");
    setSize(800, 800);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    painel = new JPanel();
    painel.setLayout(new GridLayout(linhas, colunas));
    add(painel);

    this.linhas = linhas;
    this.colunas = colunas;
    tab = new JButton[linhas][colunas];
    for (int i = 0; i < linhas; i++) {
      for (int j = 0; j < colunas; j++) {
        tab[i][j] = new JButton(MessageFormat.format("{0},{1}", i, j));
      }
    }

    for (int i = 0; i < linhas; i++) {
      for (int j = 0; j < colunas; j++) {
        painel.add(tab[i][j]);
      }
    }
  }
}
Criado 11 de maio de 2011
Ultima resposta 12 de mai. de 2011
Respostas 1
Participantes 2