首页 > 解决方案 > 有没有办法在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();
    }

任何帮助深表感谢。

标签: javaswingjframe

解决方案


首先不要让你的课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在你的问题代码中添加一个方法。


推荐阅读