Creating a JFrame to display a Checkerboard
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开发者_StackOverflow社区 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?
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());
}
It's not apropos to your assignment, but you might like to examine this alternative approach to painting a checkerboard, shown here and here.
精彩评论