我正在扩展jpanel以显示游戏板,并在底部添加Jeditorpane以保持一些状态文本。不幸的是,游戏板的功能很好,但是Jeditorpane只是一个空白的灰色区域,直到我突出显示文本为止,它将呈现出任何文本的突出显示(但其余的)。如果我正确地理解秋千,它应该可以起作用,因为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 逻辑成另一个类。这将使您能够简化您的 GameMap 通过删除 paintComponent(...)

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);
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top