gpt4 book ai didi

java - 有没有办法在 Java 中的 10x10 网格/板上随机化特定颜色?

转载 作者:行者123 更新时间:2023-12-04 03:33:28 25 4
gpt4 key购买 nike

目前,我的代码运行是为了创建一个 10x10 的棋盘,每个方 block 的颜色都是随机的,但我想要它做的是让它在整个棋盘中随机化特定颜色(红色、绿色、蓝色、黄色)。

public static class TestPane extends JPanel {

protected static final int ROWS = 10;
protected static final int COLS = 10;
protected static final int BOX_SIZE = 50;

private List<Color> colors;

public TestPane() {
int length = ROWS * COLS;
colors = new ArrayList<>(length);
for (int index = 0; index < length; index++) {
int c1 = (int) (Math.random() * 255);
int c2 = (int) (Math.random() * 255);
int c3 = (int) (Math.random() * 255);
colors.add(new Color(c1, c2, c3));
}
}

@Override
public Dimension getPreferredSize() {
return new Dimension(COLS * BOX_SIZE, ROWS * BOX_SIZE);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();

int xOffset = (getWidth() - (COLS * BOX_SIZE)) / 2;
int yOffset = (getHeight() - (ROWS * BOX_SIZE)) / 2;

System.out.println("...");
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
int index = (row * COLS) + col;
g2d.setColor(colors.get(index));
g2d.fillRect(xOffset + (col * BOX_SIZE),
yOffset + (row * BOX_SIZE),
BOX_SIZE, BOX_SIZE);
}
}
g2d.dispose();
}

非常感谢任何帮助。

最佳答案

首先不要让你的类static

其次,不要释放你的graphics对象。

接下来,对于您的特定情况,您可以拥有一系列可用颜色:

private Color[] availableColors = new Color[] {Color.YELLOW, Color.RED, Color.BLUE, Color.GREEN};

然后用随机颜色填充colors ArrayList

int length = ROWS * COLS;
colors = new ArrayList<Color>();
for (int index = 0; index < length; index++) {
int randomColor = (int) (Math.random() * availableColors.length);
colors.add(availableColors[randomColor]);
}

enter image description here

下次,不要忘记将 main 方法添加到您的问题代码中。

关于java - 有没有办法在 Java 中的 10x10 网格/板上随机化特定颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67405818/

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