gpt4 book ai didi

java - 如何用Java制作双色 table 板

转载 作者:行者123 更新时间:2023-11-29 04:54:54 34 4
gpt4 key购买 nike

在我的 Java 类(class)中,我们正在学习《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

最佳答案

您获得随机数的原因是您为每个 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)) is the same as 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);
}
}

关于java - 如何用Java制作双色 table 板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160393/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com