JPanel: à la fois mettre en œuvre ma propre paintComponent () et de rendre les enfants ne fonctionne pas

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

Question

Je l'extension d'un JPanel pour afficher un plateau de jeu, et en ajoutant un JEditorPane au fond de tenir un texte d'état. Malheureusement, le plateau de jeu rend très bien, mais JEditorPane est juste une zone grise vide jusqu'à ce que je souligne le texte, quand il sera rendu tout le texte est mis en évidence (mais pas le reste). Si je suis bonne compréhension Swing, il devrait fonctionner, parce que super.paintComponent (g) devrait rendre les autres enfants (à savoir le JEditorPane). Dites-moi, ô grand stackoverflow, quelle erreur crétin que je fais?

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
      }
    }
  }
}
Était-ce utile?

La solution

Je ne vois pas quoi que ce soit immédiatement crétin sujet de votre code en général, mais je dirais que votre hiérarchie composante semble un peu crétin.

Y at-il une raison pour laquelle vous ne sépare pas vos objets en mieux? Afin de garder votre code maintenable et testable, je vous encourage à extraire la logique de GameBoard dans une autre classe. Cela vous donnera la possibilité de faire votre GameMap en simplifier la suppression 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
}

Et puis votre GameBoard pourrait ressembler à

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);
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top