JPANEL:自分のpaintComponent()とレンダリングの子供を実装することは機能しません

StackOverflow https://stackoverflow.com/questions/2752593

質問

ゲームボードを表示するために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
      }
    }
  }
}
役に立ちましたか?

解決

私はあなたのコード全般についてすぐに骨を折ったものは何も見ませんが、あなたのコンポーネントの階層は少し骨が折れているように見えると思います。

オブジェクトをよりよく分離していない理由はありますか?あなたのコードを保守可能でテスト可能に保つために、私はあなたが抽出することをお勧めします 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