开发者

Java For Loop Inside Constructor is Infinitely Repeating

开发者 https://www.devze.com 2023-04-03 22:29 出处:网络
So, for some reason when I try to use a for loop to initialize panels in chess board, it actually loops the loop itself. In other words, it doesn\'t go on forever, but it starts and comp开发者_开发知识

So, for some reason when I try to use a for loop to initialize panels in chess board, it actually loops the loop itself. In other words, it doesn't go on forever, but it starts and comp开发者_开发知识库letes again and again.

package chessgame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChessGame extends JFrame implements ActionListener{

    public static final int WIDTH=800;
    public static final int HEIGHT=800;

    public static void main(String[] args) {
        ChessGame gui = new ChessGame();
        gui.setVisible(true);
    }
    public ChessGame(){
        super("Chess Game Demo");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(8,8));
        JPanel[] chessSquares = new JPanel[64];
        for (int a=0;a<64;a++){
            System.out.println(a);
        }
    }
}

I have included all potentially relevant code because I plan to use indices of chessSquares to color squares black and white. When I do this I also get a NullPointerException. I can understand why I'm getting that given the following error, but I cannot at all understand why a would be printed 0, 1....62, 63 over and over again. I am relatively new to Swing and have absolutely no idea why it does this. If anyone could explain that would be tremendously helpful. Thanks.


Don't put meaningful initialization in ChessGame's constructor, but instead override frameInit. When you do, also be sure to call super.frameInit(). See the javadoc or this tutorial.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号