组件必须有一个有效的对等体 - BufferStrategy
Component must have a valid peer - BufferStrategy
首先,我知道以前有人问过这样的问题,但似乎没有答案可以解决我的问题。
我正在开发一个小游戏,出于某种原因 java returns 每当我尝试创建新的缓冲策略时都会出现 IllegalStateException。我正在将游戏添加到JFrame,但仍然抛出异常,这是添加到JFrame的代码:
JFrame frame;
public Window(int x, int y, int width, int height, String title, boolean focus, Main game) throws IOException {
frame = new JFrame();
frame.setLocation(x, y);
frame.setSize(new Dimension(width, height));
frame.setTitle(title);
frame.add(game);
game.start();
frame.setAutoRequestFocus(focus);
frame.setFocusable(true);
frame.setVisible(true);
}
这里是创建 window 的代码(位于 Main class):
window = new Window(x, y, WIDTH, HEIGHT, "Title", true, this);
我假设 createBufferStrategy() 是在 game.start() 的帧上调用的。
IllegalStateException 可能会发生,因为 JFrame 在从 JVM 外部分配资源之前并不真正存在于计算机中(或类似的东西)。
当我自己尝试创建 BufferStrategy() 时,错误提示 "Component must have a valid peer"。显然,同行是图形组件的示例版本,OS 或图形管理器将其用作绘制自定义组件的原型。
我想,在您的 JFrame 被分配到 OS 中的对等体之前,它没有制作 BufferStrategy 所需的所有信息——JFrame 的大小可能在内部列为0 乘 0,也许,它不会更新为宽度乘高度,直到您告诉 JVM 使框架可显示或 "valid"。您需要在调用 game.start().
之前执行此操作
frame.setVisible(true) 将显示框架,并且显然会根据需要分配对等点。您可以在之后调用 game.start()。
如果您想在不可见的 JFrame 上调用 createBufferStrategy(),请尝试 frame.pack(),它会验证框架中的每个组件而不显示它。注意:它还会压缩框架以适合其组件——如果您还没有添加任何东西,或者还没有调用 setMinimumSize(),JFrame 将会缩小。
首先,我知道以前有人问过这样的问题,但似乎没有答案可以解决我的问题。
我正在开发一个小游戏,出于某种原因 java returns 每当我尝试创建新的缓冲策略时都会出现 IllegalStateException。我正在将游戏添加到JFrame,但仍然抛出异常,这是添加到JFrame的代码:
JFrame frame;
public Window(int x, int y, int width, int height, String title, boolean focus, Main game) throws IOException {
frame = new JFrame();
frame.setLocation(x, y);
frame.setSize(new Dimension(width, height));
frame.setTitle(title);
frame.add(game);
game.start();
frame.setAutoRequestFocus(focus);
frame.setFocusable(true);
frame.setVisible(true);
}
这里是创建 window 的代码(位于 Main class):
window = new Window(x, y, WIDTH, HEIGHT, "Title", true, this);
我假设 createBufferStrategy() 是在 game.start() 的帧上调用的。
IllegalStateException 可能会发生,因为 JFrame 在从 JVM 外部分配资源之前并不真正存在于计算机中(或类似的东西)。
当我自己尝试创建 BufferStrategy() 时,错误提示 "Component must have a valid peer"。显然,同行是图形组件的示例版本,OS 或图形管理器将其用作绘制自定义组件的原型。
我想,在您的 JFrame 被分配到 OS 中的对等体之前,它没有制作 BufferStrategy 所需的所有信息——JFrame 的大小可能在内部列为0 乘 0,也许,它不会更新为宽度乘高度,直到您告诉 JVM 使框架可显示或 "valid"。您需要在调用 game.start().
之前执行此操作frame.setVisible(true) 将显示框架,并且显然会根据需要分配对等点。您可以在之后调用 game.start()。
如果您想在不可见的 JFrame 上调用 createBufferStrategy(),请尝试 frame.pack(),它会验证框架中的每个组件而不显示它。注意:它还会压缩框架以适合其组件——如果您还没有添加任何东西,或者还没有调用 setMinimumSize(),JFrame 将会缩小。