代码之家  ›  专栏  ›  技术社区  ›  PotatoEngineer

jpanel:实现自己的paintcomponent()和渲染子级都不起作用

  •  0
  • PotatoEngineer  · 技术社区  · 15 年前

    我正在扩展一个jpanel来显示一个游戏板,并在底部添加一个jeditorpane来保存一些状态文本。不幸的是,游戏板渲染得很好,但jeditorpane只是一个空白的灰色区域,直到我突出显示其中的文本,当它将渲染突出显示的任何文本时(而不是其余部分)。如果我理解Swing是正确的,它应该是有效的,因为super.paintcomponent(g)应该渲染其他的孩子(即jeditorpane)。告诉我,哦,大堆垛,我犯了什么愚蠢的错误?

    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
          }
        }
      }
    }
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Mike    15 年前

    一般来说,我看不到任何关于代码的愚蠢之处,但我会说,您的组件层次结构似乎有点愚蠢。

    你为什么不把你的物品分开呢?为了保持代码的可维护性和可测试性,我建议您提取 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
    }
    

    然后你的 游戏板 可能看起来像

    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);
      }
    }