views:

163

answers:

1

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
      }
    }
  }
}
+2  A: 

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 your GameMap by removing the 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
}

And then your GameBoard might look like

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);
  }
}
Mike
As I was running through solutions, I found that your method worked just fine to solve it, and did indeed separate out the code better. See my comment on the question about a) the not-actually-mentioned-in-the-question *real* problem, and b) my being a pillock.
Paul Marshall