繁体   English   中英

如何用Java制作双色桌板

[英]How to make a bicolor table board in Java

在我的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);

    }

}

在此输入图像描述

获得随机数的原因是因为您为每个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
    }
}

输出类似于:

在此输入图像描述


编辑

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM