java - 有没有办法在java中随机化10x10网格/板上的特定颜色?
问题描述
目前,我的代码运行以便它为每个方块创建一个随机颜色的 10x10 板,但我想要它做的是让它在整个板上随机化特定颜色(红色、绿色、蓝色、黄色)。
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]);
}
下一次,别忘了main
在你的问题代码中添加一个方法。
推荐阅读
- reactjs - React - 如何定位特定的组件实例
- javascript - 如何通过发布请求循环值?
- css - 溢出时元素会换行到下一行
- spring-boot - 多对多条件查询
- flutter - Flutter / Moor 在尝试构建我的数据模型时出现动态函数返回类型错误
- ios - 将凭据喜欢的用户名和密码保存在 swift 文件中是否安全
- android - 错误:找不到字段的设置器。- java.util.ArrayList 中的大小 - Room 中的嵌入式 ArrayList 无法编译
- reactjs - 无法读取 React js 中的属性
- php - 如何使用oracle数据库在php中获取特定行和列中的数据
- django - Docker 和 Django PermissionError:运行 collectstatic 时的 [Errno 13]