JPanel:实现我自己的 PaintComponent() 和渲染子项都不起作用
我扩展 JPanel 来显示游戏板,并在底部添加 JEditorPane 来保存一些状态文本。不幸的是,游戏板渲染得很好,但 JEditorPane 只是一个空白的灰色区域,直到我突出显示其中的文本,此时它将渲染突出显示的任何文本(但不渲染其余文本)。如果我对 Swing 的理解正确,它应该可以工作,因为 super.paintComponent(g) 应该渲染其他子项(即 JEditorPane)。告诉我,伟大的 stackoverflow,我犯了什么愚蠢的错误?
public GameMap extends JPanel {
public GameMap() {
JEditorPane statusLines = new JEditorPane("text/plain","Stuff");
this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
this.add(new Box.Filler(/*enough room to draw my game board*/));
this.add(statusLines);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for ( all rows ){
for (all columns){
//paint one tile
}
}
}
}
I'm extending a JPanel to display a game board, and adding a JEditorPane at the bottom to hold some status text. Unfortunately, the game board renders just fine, but the JEditorPane is just a blank gray area until I highlight the text in it, when it will render whatever text is highlighted (but not the rest). If I'm understanding Swing right, it should work, because super.paintComponent(g) should render the other children (i.e., the JEditorPane). Tell me, o great stackoverflow, what bonehead mistake am I making?
public GameMap extends JPanel {
public GameMap() {
JEditorPane statusLines = new JEditorPane("text/plain","Stuff");
this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
this.add(new Box.Filler(/*enough room to draw my game board*/));
this.add(statusLines);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for ( all rows ){
for (all columns){
//paint one tile
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,我没有看到你的代码有任何立即愚蠢的地方,但我想说你的组件层次结构似乎有点愚蠢。
您没有更好地分离对象是否有原因?为了保持代码的可维护性和可测试性,我鼓励您将 GameBoard 逻辑提取到不同的类中。这将使您能够通过删除
paintComponent(...)
来简化您的GameMap
然后您的
GameBoard
可能看起来像I don't see anything immediately boneheaded about your code in general, but I would say that your component hierarchy seems a bit boneheaded.
Is there a reason why you aren't separating your objects out better? In order to keep your code maintainable and testable, I'd encourage you to extract
GameBoard
logic into a different class. This would give you the ability to do simplify yourGameMap
by removing thepaintComponent(...)
And then your
GameBoard
might look like