java - 绘制到 BufferStrategy Java 时遇到问题
问题描述
我正在创建一个游戏,并想使用它的 BufferStrategy 绘制到 Canvas。由于某种原因,它似乎不想在屏幕上显示任何内容。我查看了 Java 文档并阅读了其他人提出的几个 Stackoverflow 问题,但无法使其正常工作。只想显示黑色背景,以便我知道它正在工作。
这是我创建画布的地方:
public static void createDisplay() {
if (frame != null)
return;
URL path = Display.class.getResource(ICON_PATH);
Image icon = Toolkit.getDefaultToolkit().getImage(path);
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsConfiguration config = env.getDefaultScreenDevice().getDefaultConfiguration();
Display.frame = new Frame(FRAME_TITLE, config);
Display.canvas = new Canvas(config);
frame.setMinimumSize(MIMIMUM_FRAME_SIZE);
frame.setIconImage(icon);
frame.addWindowListener(this); // For closing frame
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.add(canvas);
frame.setVisible(true);
}
这里是我尝试显示黑色背景的地方:
public void drawFrame() {
Canvas canvas = Display.getCanvas();
BufferStrategy strat = canvas.getBufferStrategy();
if (strat == null) {
canvas.createBufferStrategy(3);
return;
}
do {
do {
Graphics2D g = null;
int screenWidth = canvas.getWidth();
int screenHeight = canvas.getHeight();
try {
g = (Graphics2D) strat.getDrawGraphics();
g.clearRect(0, 0, screenWidth, screenHeight);
//BufferedImage map = loader.loadWorld();
g.setBackground(Color.black);
//g.drawImage(map, 0, 0, canvas);
} finally {
g.dispose();
}
} while (strat.contentsRestored());
strat.show();
} while (strat.contentsLost());
}
drawFrame() 在我的游戏循环中被多次调用,而 createDisplay() 在游戏循环开始之前被调用一次。当我运行我的游戏时,我得到的只是一个带有空白屏幕的框架:
感谢您的帮助。
解决方案
好的,所以我将JFrame更改为Frame,这样我就不会将 swing 组件与 awt 组件混合在一起。此外,我调用g.setBackground(color)
它并没有在屏幕上绘制任何内容,所以我只是简单地将图形颜色设置为g.setColor(color)
. 然后我用g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight())
.
这是我的新 drawFrame() 方法:
public void drawFrame() {
Canvas canvas = Display.getCanvas();
BufferStrategy strat = canvas.getBufferStrategy();
if (strat == null) {
canvas.createBufferStrategy(3);
return;
}
do {
do {
Graphics2D g = null;
int screenWidth = canvas.getWidth();
int screenHeight = canvas.getHeight();
try {
g = (Graphics2D) strat.getDrawGraphics();
g.setColor(Color.black); // Set Graphics Color
g.fillRect(0, 0, screenWidth, screenHeight); // Fill Background
// Do All Drawing here
} finally {
g.dispose();
}
} while (strat.contentsRestored());
strat.show();
Toolkit.getDefaultToolkit().sync(); // Also added this to synchronize graphics state
} while (strat.contentsLost());
}
推荐阅读
- shopify - 将产品限制为每位客户仅一件
- arrays - 从 foreach 循环中的爆炸数组字段获取数组对象数据
- android - 从位图创建 Exifinterface
- node.js - 用于 Google Cloud Functions 身份验证重定向的 gitHubAutoDeployer
- android - 当我在 JNI 中拼接字符串时“检测到堆损坏”
- lua - 您可以将实例保存在表中吗?
- c++ - 同一类函数的多个定义取决于同一继承类的多个类型?
- r - R中的代码仅对列的一部分求和(由行定义的组)
- ruby-on-rails - 如何将 gem 安装位置更改为正确的位置?
- python - 将文件列表转换为树状字典