gpt4 book ai didi

java - 双缓冲 JFrame

转载 作者:行者123 更新时间:2023-11-29 06:03:19 28 4
gpt4 key购买 nike

在开发 2D 游戏时,我阅读了很多有关双缓冲的文章。我遇到过许多不同的实现策略,但不确定双缓冲如何适合我创建游戏窗口的方式。例如,我看到的一篇文章 (http://content.gpwiki.org/index.php/Java:Tutorials:Double_Buffering) 建议使用单独的绘图方法;但是,我怀疑如果您要绘制形状而不是向窗口添加组件,这将适用。

这是我的主要 GUI 代码(省略了 keylistener 方法)

public class MainWindow extends JFrame implements KeyListener{
private Dimension dim;
private CardLayout layout;
private JPanel panel;
private JLayeredPane gameLayers;
private Menu menu;
private MiniGame miniGame;
private Board board;
private Sprite sprite;
private Game game;
private Map map;
private GameState gs;

private Boolean[] keys;


public MainWindow(Game game, GameState gs, Map map, Sprite sprite){
//Call superclass.
super();

addKeyListener(this);

//Sore references to critical game components.
this.game = game;//So we can call methods when an event occurs.
this.gs = gs;
this.map = map;//Used to construct the board.
//The board needs to know the layout of the map.
this.sprite = sprite;//Used to add the sprite to one of the layers.

//Instantiate objects.
dim = new Dimension(800, 600);
layout = new CardLayout();
panel = new JPanel(layout);
menu = new Menu();
miniGame = new MiniGame();
board = new Board(map);
gameLayers = new JLayeredPane();

//Remove decoration and place window in center of screen.
setUndecorated(true);
Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenDim.width /2)-(dim.width/2),
(screenDim.height/2)-(dim.height/2),
dim.width,
dim.height);

//Add the board to a layer.
gameLayers.add(board, JLayeredPane.DEFAULT_LAYER);
board.setBounds(0, 0, dim.width, dim.height);
board.setBoard();

//Add the sprite to a layer.
gameLayers.add(sprite, JLayeredPane.PALETTE_LAYER);
sprite.setBounds(0, 0, 50, 50);

//Add components to window.
panel.add(gameLayers, "gameLayers");
panel.add(miniGame, "miniGame");
panel.add(menu, "menu");

//Add the "cards" to the window.
add(panel);

//JFrame housekeeping.
pack();
setSize(dim);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);

//Holds state when an event is triggered.
//Ugly hack to circumvent delay issue.
keys = new Boolean[4];
for(int i=0; i<keys.length; i++){
keys[i] = false;
}
}
}

您建议我如何处理这个问题?请记住,Board 是一个由缩放图像网格组成的 JPanel,而 sprite 将是一个显示缩放图像的 JComponent。

问候, jack 。

最佳答案

覆盖 JPanel 的 paintComponent() 方法并将内容绘制到 BufferedImage 中图像第一。完成后,将 BufferedImage 的内容复制到您从 paintComponent() 获得的图形上下文中。

protected void paintComponent(Graphics g) 
{
BufferedImage bufferedImage = new BufferedImage(500, 500, BufferedImage.TYPE_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
//paint using g2d ...

Graphics2D g2dComponent = (Graphics2D) g;
g2dComponent.drawImage(bufferedImage, null, 0, 0);
}

关于java - 双缓冲 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367502/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com