我正在扩展 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
}
}
}
}
最佳答案
一般来说,我没有看到您的代码有任何立即愚蠢的地方,但我想说您的组件层次结构似乎有点愚蠢。
您没有更好地分离对象是否有原因?为了保持代码的可维护性和可测试性,我鼓励您将 GameBoard 逻辑提取到不同的类中。这将使您能够通过删除 paintComponent(...)
GameMap
public class GameMap extends JPanel{
private JEditorPane status;
private GameBoard board;
public GameMap() {
status= createStatusTextPane();
board = new GameBoard();
this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
this.add(board);
this.add(status);
}
//...all of the other stuff in the class
// note that you don't have to do anything special for painting in this class
}
然后你的GameBoard
可能看起来像
public class GameBoard extends JPanel {
//...all of the other stuff in the class
public void paintComponent(Graphics g) {
for (int row = 0; row < numrows; row++)
for (int column = 0; column < numcolumns ; column ++)
paintCell(g, row, column);
}
}
关于java - JPanel:实现我自己的 PaintComponent() 和渲染子项都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2752593/