我现在编写了一个简单的RTS游戏,这是我第一次体验游戏设计。我的问题是,当我使用 createBufferStrategy(2) 时,所有 swing 元素(按钮等...)在 bufferStrategy.show(); 之后不会显示。方法被调用。我的游戏充满了按钮、表格和其他垃圾,我真的不想自己编写所有这些代码。另外,我真的很喜欢 Java 的布局,并且想在此基础上制作所有 GUI。 所以,这里有一些代码示例,不是来 self 的游戏,但它很好地演示了我的问题。谢谢。 顺便说一句,我了解问题的根源。我知道 Swing 绘制机制是基于事件的,而使用缓冲区策略不是基于事件的。但我不知道如何解决这个问题。谢谢。 最后 - 我不想使用默认的基于 Swing 事件的方法,因为它对于游戏来说很慢,并且据我所知,缓冲策略只是游戏的方法。谢谢。
public static void main(String[] args){
final JFrame frame = new JFrame();
JPanel menuPanel = new JPanel();
final Button button = new Button("Exit");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menuPanel.add(button);
frame.add(menuPanel);
frame.setPreferredSize(new DimensionUIResource(800, 600));
//frame.setResizable(false);
//frame.setUndecorated(true);
//frame.setIgnoreRepaint(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final long delay = 1000/60;
frame.pack();
frame.setVisible(true);
final GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (device.isFullScreenSupported()){
device.setFullScreenWindow(frame);
// this place. If I turn into fullscreen mode button disappear. And if I stay in windowed mode button exist and work;
}
frame.createBufferStrategy(2);
final BufferStrategy bufferStrategy = frame.getBufferStrategy();
Thread renderingThread = new Thread(){
public void run(){
while (true){
long startRenderingTime = System.currentTimeMillis();
Graphics g = bufferStrategy.getDrawGraphics();
g.setColor(Color.white);
g.fillRect(0,0,1680,1050);
//button.paint(g);
//button.paintAll(g);
// I don't know how to draw button!
g.dispose();
if (!bufferStrategy.contentsLost()){
bufferStrategy.show();
}
long endRenderingTime = System.currentTimeMillis();
long actionTime = endRenderingTime-startRenderingTime;
try {
if (actionTime>delay){
sleep(5);
} else {
sleep(delay-actionTime);
}
} catch (InterruptedException e){
return;
}
}
}
};
renderingThread.start();
}
});
}
最佳答案
您正在 Swings EDT 上运行无限循环,从而有效地阻止 Swing 执行任何操作。
当您想要显示 Swing 元素时,我不知道您甚至不需要 BufferStrategy。要将自定义呈现与 Swing 组件结合起来,您通常只需创建一个呈现您的内容的组件并将其添加到正常布局中。
你的组件只是覆盖paintComponent()并绘制它需要的任何内容。您可以通过调用 repaint() 轻松触发组件的更新。这通常表现得足够好。请注意,Swing 组件默认情况下是双缓冲的,因此不需要在那里使用 BufferStrategy。
如果您想坚持主动渲染,您可以有选择地调用 Swings 渲染链,例如,您可以获取 Frame 的 ContentPane 并在渲染循环中调用 Paint()。但以这种方式破解可能会导致不必要的副作用。
关于java - 同时使用java bufferstrategy和swing元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24456513/