Creating a JFrame to display a Checkerboard

2019-08-13 01:53发布

My assignment is to detailed as follows:

The goal is to put a checker board in a window on the screen. I am given two classes called PicturePanel and Pixel

the class PicturePanel extends JPanel with a little bit more functionality using a class called Pixel

my idea for completing this task was to make fifty square PicturePanels of each color and alternately add them onto one large panel then add that panel to my JFrame object.

here is my code:

public class BlueSquare extends PicturePanel
{

    public BlueSquare()
    {
     this.setSize(50,50);
     setAllPixelsToAColor(0,0,255);
    }

}  


public class RedSquare extends PicturePanel
{

    public RedSquare()
    {
     this.setSize(50,50);
     setAllPixelsToAColor(0,255,0);
    }

}  

public class BigPanel extends PicturePanel 
{   
    public BigPanel()
    {
    RedSquare rs = new RedSquare();
    BlueSquare bs = new BlueSquare();

     for(int i=0; i<50;i++ )
     {
      add(rs);
      add(bs);
     }
}

public class CheckerBoard extends JFrame
{

   public CheckerBoard()
   {
    setTitle("Checker Board");
    setSize(500,500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BigPanel bp = new BigPanel();

    add(bp);
    this.setVisible(true);

   }


   public static void main(String args[])
   {
       CheckerBoard cb = new CheckerBoard();

   }
}

When run it only displays a white box and a red box

how can I format the Checkerboard to see the two colors?

2条回答
【Aperson】
2楼-- · 2019-08-13 02:13

It's not apropos to your assignment, but you might like to examine this alternative approach to painting a checkerboard, shown here and here.

查看更多
相关推荐>>
3楼-- · 2019-08-13 02:28

You are adding the same two squares again and again. Instead create new squares in the loop and add them. Example:

for(int i=0; i<50;i++ ){
    add(new RedSquare());
    add(new BlueSquare());

}
查看更多
登录 后发表回答