gpt4 book ai didi

java - Bufferstrategy 未显示在 java.awt.Frame 上

转载 作者:行者123 更新时间:2023-12-01 10:36:33 25 4
gpt4 key购买 nike

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 将返回要使用的下一个缓冲区,因此您要更改不同缓冲区的属性。

第二,在缓冲区上绘制和 native 对等点再次绘制窗口之间存在竞争条件,从而覆盖缓冲区的内容。

这个示例基本上设置了一个无限更新循环,它会重新绘制缓冲区,您可以减慢延迟,并且可以看到它从一种状态更改为另一种状态

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,这将阻止您在框架边框下绘画并为您提供更好地了解您可以绘制的实际可视空间

关于java - Bufferstrategy 未显示在 java.awt.Frame 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689176/

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