JPANEL: كلاهما ينفذ PaintComponent () وتقديم الأطفال لا يعمل

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

سؤال

أقوم بتمديد JPanel لعرض لوحة ألعاب ، وإضافة Jeditorpane في الأسفل لعقد بعض نص الحالة. لسوء الحظ ، فإن لوحة اللعبة تجعل على ما يرام ، لكن Jeditorpane هي مجرد منطقة رمادية فارغة حتى أقوم بتسليط الضوء على النص فيه ، عندما يتم تسليط الضوء على أي نص (ليس الباقي). إذا كنت أفهم التأرجح بشكل صحيح ، فيجب أن ينجح ، لأن Super.PaintComponent (G) يجب أن يجعل الأطفال الآخرين (أي ، Jeditorpane). قل لي ، يا stackoverflow الرائع ، ما الخطأ الذي ارتكبه؟

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