Java 中的像素网格动画

Animating a Grid of Pixels in Java

我是一名新手程序员,我正在研究 a little project,它涉及一个 1000 x 1000 布尔值的二维网格,该网格根据指令模式发生变化。 "After x instructions, how many values in the grid are true?" 那种事。

我想稍微调整一下,将值渲染为像素网格,如果相应的值为假,则为黑色,如果为真,则为白色,并且在处理指令时实时动画,但我很迷茫——我从未涉足 Java 中的 2D 图形。我通读了 Oracle's tutorial,这对我有所帮助,但我做事的方式与其演示完全不同,我仍然感到迷茫。

我最直接的问题是我什至无法使用 BufferedImage 初始化 1000 x 1000 黑色像素的网格。 运行 我的代码生成了一个非常小的 window,其中没有任何内容(灰色)。谁能告诉我我做错了什么并建议如何进行?我的代码如下:

import java.awt.image.BufferedImage;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PixelGrid extends JPanel {

    private BufferedImage grid;

    // Ctor initializing a grid of binary (black or white) pixels
    public PixelGrid(int width, int height) {
        grid = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
    }

    /**
     * Fill an area with a given color
     * @param color 0 for black; 1 for white
     * @param x1 Starting x coordinate
     * @param y1 Starting y coordinate
     * @param x2 Ending x coordinate
     * @param y2 Ending y coordinate
     */
    public void toggleBlock(int color, int x1, int y1, int x2, int y2) {
        if (color == 0) {
            color = Color.BLACK.getRGB();
        }
        else {
            color = Color.WHITE.getRGB();
        }
        for (int x = x1; x <= x2; x++) {
            for (int y = y1; y <= y2; y++) {
                grid.setRGB(x, y, color);
            }
        }
    }

    // Clear the grid (set all pixels to black)
    public void clear() {
        toggleBlock(0, 0, 0, grid.getWidth() - 1, grid.getHeight() - 1);
    }

    public static void main(String[] args) {
        int width = 1000;
        int height = 1000;
        PixelGrid aGrid = new PixelGrid(width, height);
        JFrame window = new JFrame("A Wild Pixel Grid Appears!");

        window.add(aGrid); // Incorporates the pixel grid into the window
        window.pack(); // Resizes the window to fit its content
        window.setVisible(true); // Makes the window visible
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

请注意,它还没有处理实际的二维布尔数组或指令处理;我很确定我可以自己处理,但是,现在,我只是想了解如何设置图形组件。

您的代码创建了一个 BufferedImage,但随后没有对它执行任何操作(以图形方式)。几个选项:

选项 1:覆盖 PixelGrid class 的 paintComponent 并将图像绘制到 JPanel

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(grid, 0, 0, this);
}

选项 2:使用 JLabelImageIcon

JLabel label = new JLabel(new ImageIcon(grid));
add(label);

在任何一种情况下,每次更改 BufferedImage 时都必须在组件上调用 repaint

//some code
    grid.setRGB(x, y, color);
//some more code
repaint();//or label.repaint() if Option 2