微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决有没有办法在 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]);
}

enter image description here

下次不要忘记在问题代码中添加 main 方法。

,

制作一个长度与棋盘上的字段一样长的所需颜色数组,然后使用 Collections.shuffle(list); 对该数组进行混洗,然后将混洗后的颜色数组应用到棋盘上。

要在改组之前制作第一个数组,请重复以下颜色:[red,green,blue,yellow,red,...]

,

没有很多特定的颜色,但您可以尝试使用以下颜色:

Random r = new Random();
Color c = new Color(r.nextInt(3)*127,r.nextInt(3)*127,r.nextInt(3)*127);

这应该会为您提供更具体的颜色。如果您希望它们更具体(但数量较少),请使用 r.nextInt(1)*255

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。