创建一个JFrame以显示一个棋盘 [英] Creating a JFrame to display a Checkerboard

查看:99
本文介绍了创建一个JFrame以显示一个棋盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务如下:

目标是将棋盘格放在屏幕上的窗口中. 我得到了两个叫做PicturePanel和Pixel的类

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

PicturePanel类使用名为Pixel的类扩展了JPanel的功能

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

我完成此任务的想法是制作每种颜色的五十个正方形PicturePanel,并将它们交替添加到一个大面板上,然后将该面板添加到我的JFrame对象中.

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.

这是我的代码:

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());

}

这篇关于创建一个JFrame以显示一个棋盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆