如何解决我正在尝试在 Java 中渲染一个蓝色方块,但出现 IllegalStateException 错误有人能帮我吗?
我试图在 Java 中将一个蓝色方块渲染到屏幕上,但蓝色方块没有显示出来,而且我得到了一个 IllegalStateException
。
创建窗口类
package Graphics;
import java.awt.Dimension;
import javax.swing.JFrame;
public class CreateWindow {
public CreateWindow(int width,int height,String title) {
Dimension d = new Dimension();
JFrame frame;
d.width = width;
d.height = height;
frame = new JFrame();
frame.setPreferredSize(d);
frame.setMinimumSize(d);
frame.setMaximumSize(d);
frame.setResizable(false);
frame.setTitle(title);
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeto(null);
frame.setVisible(true);
new BufferedImageOperation();
}
public void deleteWindow() {}
public static void main(String[] args) {
new CreateWindow(500,500,"POOP");
}
}
BufferedImageOperation 类
package Graphics;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class BufferedImageOperation extends Canvas {
private static final long serialVersionUID = 1L;
public BufferedImageOperation() {
render();
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLUE);
g.drawRect(0,32,32);
g.dispose();
bs.show();
}
}
控制台是这样说的:
Exception in thread "main" java.lang.IllegalStateException: Component must have a valid peer
at java.desktop/java.awt.Component$FlipBufferStrategy.createBuffers(Component.java:4106)
at java.desktop/java.awt.Component$FlipBufferStrategy.<init>(Component.java:4080)
at java.desktop/java.awt.Component$FlipSubRegionBufferStrategy.<init>(Component.java:4608)
at java.desktop/java.awt.Component.createBufferStrategy(Component.java:3943)
at java.desktop/java.awt.Canvas.createBufferStrategy(Canvas.java:195)
at java.desktop/java.awt.Component.createBufferStrategy(Component.java:3867)
at java.desktop/java.awt.Canvas.createBufferStrategy(Canvas.java:170)
at Graphics.BufferedImageOperation.render(BufferedImageOperation.java:17)
at Graphics.BufferedImageOperation.<init>(BufferedImageOperation.java:12)
at Graphics.CreateWindow.<init>(CreateWindow.java:30)
at Graphics.CreateWindow.main(CreateWindow.java:39)
解决方法
了解异常在哪里抛出很重要,但我怀疑 BufferedImageOperation
不可见,未添加到任何(可见)组件中,
例如:frame.add(new BufferedImageOperation());
。
编辑:检查 createBufferStrategy()
:
throws IllegalStateException
- 如果组件不可显示
和isDisplayable()
:
当一个组件被添加到一个可显示的包含层次结构或者当它的包含层次结构被设置为可显示时,它就会被设置为可显示的。当其祖先窗口被打包或可见时,包含层次结构将变为可显示。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。