Question

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
      }
    }
  }
}
Was it helpful?

Solution

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);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top