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

发布于 2015-12-09 00:56:33
获得随机数的原因是您为每个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在他的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);
}
}https://stackoverflow.com/questions/34160393
复制相似问题