如何用Java制作双色桌板

时间:2015-12-08 15:59:57

标签: java swing

在我的Java课程中,我们正在阅读Java基础知识的第4章。我正在做4-11项目,这是一个黑色和红色的棋盘,但是我得到了随机颜色,我试图按照本书教我们使用ColorPanels和JFrames的方式完成这个。这是我的代码:

package guiwindow3;
import javax.swing.*;
import java.awt.*;
import java.util.*;

public class GUIWindow3 {

    public static void main(String[] args) {

        //Objects
        JFrame theGUI = new JFrame();

        //Format GUI
        theGUI.setTitle("GUI Example");

        theGUI.setSize(500, 500);
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container pane = theGUI.getContentPane();
        pane.setLayout(new GridLayout(8, 8));

        //Loop for grid
        Color lastColor = Color.BLACK;

        for(int i = 1; i < 8; i++) {

            for(int j = 0; j < 8; j++) {

                if((j % 2 == 1 && i %2 == 1) || (j % 2 == 0 && i % 2 == 0)) {

                    lastColor = Color.RED;

                }

                else {

                    lastColor = Color.BLACK;

                }

                ColorPanel panel = new ColorPanel(lastColor);

                pane.add(panel);

            }

        }

        theGUI.setVisible(true);

    }

}

然后对于ColorPanel类,我有:

import javax.swing.*;
import java.awt.*;

class ColorPanel extends JPanel {

    public ColorPanel(Color lastColor) {

        setBackground(lastColor);

    }

}

enter image description here

1 个答案:

答案 0 :(得分:3)

您获取随机数的原因是您为每个RGB参数创建了一个随机数。相反,你可以改变这个:

for (int i = 1; i <= rows * cols; i++) {
    int red = gen.nextInt(256); //A random Red 
    int green = gen.nextInt(256); //A random Green
    int blue = gen.nextInt(256); //A random Blue
    Color backColor = new Color(red, green, blue); //Join them and you get a random color
    ColorPanel panel = new ColorPanel(backColor); //Paint the panel
    pane.add(panel);
}

对此:

Color lastColor = Color.BLACK;
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
            lastColor = Color.RED; //Set the color to RED
        } else {
            lastColor = Color.BLACK; //Set the color to BLACK
        }
        ColorPanel panel = new ColorPanel(lastColor); //Paint the panel with RED or BLACK color
        pane.add(panel); //Add the painted Panel
    }
}

输出类似于:

enter image description here

修改

获得相同输出并使if条件更容易阅读的另一种方法是@ dimo414在他的comment中说:

  

if((j % 2 == 1 && i %2 == 1) || (j % 2 == 0 && i % 2 == 0))if (j % 2 == i % 2)

相同
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (i % 2 == j % 2) {
            lastColor = Color.RED;
        } else {
            lastColor = Color.BLACK;
        }
        ColorPanel panel = new ColorPanel(lastColor);
        pane.add(panel);
    }
}