在Java中动画像素网格

时间:2016-06-29 19:29:17

标签: java swing animation jframe jpanel

我是一个noob程序员,我正在研究a little project,它涉及一个基于指令模式而改变的1000 x 1000布尔值的2D网格。 "在x指令后,网格中有多少个值是真的?"那种事。

我想对它进行一点点旋转并将值渲染为像素网格,如果它们的对应值为假,则为黑色;如果它们为真,则为白色,并且在处理指令时实时动画化,但我很丢失 - 我从来没有涉及过Java中的2D图形。我阅读了Oracle's tutorial,这有帮助,但我做事情的方式与我仍然感到失落的演示完全不同。

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

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);
    }

}

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

1 个答案:

答案 0 :(得分:3)

您的代码会创建BufferedImage,但之后不会对其执行任何操作(以图形方式)。一些选择:

选项1 :覆盖paintComponent类的PixelGrid并将图片绘制到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时都必须在Component上调用repaint

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