Bufferstrategy没有显示在java.awt.Frame上

public void configure() { Frame frame = ctx.getFrame(); frame.setTitle("AstroCycles | By: Carlos Aviles"); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setFocusable(true); frame.setSize(WIDTH, HEIGHT); frame.addKeyListener(ctx.getKeyEventDispatcher()); frame.addWindowListener(ctx.getWindowEventDispatcher()); frame.addMouseListener(ctx.getMouseEventDispatcher()); frame.setVisible(true); frame.createBufferStrategy(3); frame.getBufferStrategy().getDrawGraphics().setColor(Color.RED); frame.getBufferStrategy().getDrawGraphics().fillRect(0, 0, 75, 75); frame.getBufferStrategy().getDrawGraphics().dispose(); frame.getBufferStrategy().show(); } 

框架正在显示,但框架上未显示具有所请求坐标和大小的矩形(红色)。 我不知道为什么它不是画画。 控制台没有抛出任何错误。 BufferStrategy也不是null。

因此,有两件事情跳出来,一, getBufferStrategy将返回要使用的下一个缓冲区,因此您要更改不同缓冲区的属性。

二,在绘制缓冲区和本地对等体再次绘制窗口之间存在竞争条件,覆盖缓冲区的内容。

这个例子基本上设置了一个无限的更新循环来重新绘制缓冲区,你可以减慢延迟,你可以看到它从一个状态变为另一个状态

 import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.util.logging.Level; import java.util.logging.Logger; public class Test { public static void main(String[] args) { Frame frame = new Frame(); frame.setTitle("AstroCycles | By: Carlos Aviles"); frame.setLocationRelativeTo(null); frame.setFocusable(true); frame.setSize(100, 100); frame.setBackground(Color.BLUE); frame.setVisible(true); frame.createBufferStrategy(3); do { BufferStrategy bs = frame.getBufferStrategy(); while (bs == null) { System.out.println("buffer"); bs = frame.getBufferStrategy(); } do { // The following loop ensures that the contents of the drawing buffer // are consistent in case the underlying surface was recreated do { // Get a new graphics context every time through the loop // to make sure the strategy is validated System.out.println("draw"); Graphics graphics = bs.getDrawGraphics(); // Render to graphics // ... graphics.setColor(Color.RED); graphics.fillRect(0, 0, 100, 100); // Dispose the graphics graphics.dispose(); // Repeat the rendering if the drawing buffer contents // were restored } while (bs.contentsRestored()); System.out.println("show"); // Display the buffer bs.show(); // Repeat the rendering if the drawing buffer was lost } while (bs.contentsLost()); System.out.println("done"); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } while (true); } } 

一个更好的解决方案是使用Canvas并将其添加到框架并使用它的BufferStrategy ,这将阻止您在框架的边框下绘画,并让您更好地了解可以绘制的实际可视空间