使用 ImageIcon 磁贴在 JPanel 上进行主动渲染? #Java

Active rendering on a JPanel with ImageIcon tiles? #Java

所以我正在尝试编写一个基于拼贴网格的游戏并提出了一个非常不寻常的解决方案。我用 JLabels 填充了 2D JPanel 数组,并以 ImageIcon 作为图块。到目前为止一切正常,但我没有找到任何方法来积极地呈现它。 我已经尝试了一些在 Internet 上找到的主动渲染方法,但它们没有按照我的想法工作。您是否有一些想法如何在不将所有内容重写为 Canvas 或类似内容的情况下实现这一点?

这是我的代码:

Window

public class Win extends JFrame {
private static final long serialVersionUID = 1L;
private BufferStrategy bs;

public Win(int x, int y) {

    this.setSize(x, y);
    this.setVisible(true);
    this.setResizable(false);
    this.setIgnoreRepaint(true);
    this.createBufferStrategy(2);
    setBs(getBufferStrategy());
}

public BufferStrategy getBs() {
    return bs;
}

public void setBs(BufferStrategy bs) {
    this.bs = bs;
}
}

"Draw"

public class Field extends JPanel {
private static final long serialVersionUID = 5257799495742189076L;

private int x = 0;
private int y = 0;
private JPanel backPanel[][] = new JPanel[19][19];
private BufferedImage images[] = new BufferedImage[100];
private JLabel image[][] = new JLabel[19][19];

public Field() {

    this.setLayout(new GridLayout(20, 20));
    this.setIgnoreRepaint(true);

}

// Creates Panel Grid & Draws floor
public void setPanels() {
    for (int h = 0; h < 19; h++) {
        for (int w = 0; w < 19; w++) {

            backPanel[h][w] = new JPanel();
            backPanel[h][w].setLayout(new GridLayout(1, 1));

            image[h][w] = new JLabel(new ImageIcon(images[0]));

            backPanel[h][w].add(image[h][w]);

            this.add(backPanel[h][w]);
        }
    }
}

// Loads the Textures
public void getTextures() throws IOException {
    for (int i = 0; i < 1; i++) {
        images[i] = ImageIO.read(new File("texture.png"));

    }
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(images[1], 0, 0, null);

}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

}

游戏循环

public class GameLoop implements Runnable {

private boolean runFlag = true;

@Override
public void run() {
    Field field = new Field();
    Win window = new Win(640, 640);
    window.add(field);

    try {
        field.getTextures();
    } catch (IOException e) {

        e.printStackTrace();
    }

    while (runFlag) {

        try {
            field.setPanels();
            window.getBs().show();
            Thread.sleep(20);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }

}

public void stop() {
    runFlag = false;
}

}

一些备选方案:

  • 打乱 组件 并执行 removeAll()add()validate(),如图所示 here .

  • 随机播放内容并执行setIcon(),如图here

无论哪种情况,

  • 使用javax.swing.Timer来调整动画的节奏,如图herehere.

  • 考虑TexturePaint填充图标,如图here