java - JPanel:实现我自己的 PaintComponent() 和渲染子项都不起作用

标签 java swing jpanel paintcomponent

我正在扩展 JPanel 来显示游戏板,并在底部添加 JEditorPane 来保存一些状态文本。不幸的是,游戏板渲染得很好,但 JEditorPane 只是一个空白的灰色区域,直到我突出显示其中的文本,此时它将渲染突出显示的任何文本(但不渲染其余文本)。如果我对 Swing 的理解正确,它应该可以工作,因为 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 逻辑提取到不同的类中。这将使您能够通过删除 paintComponent(...)

来简化您的 GameMap
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);
  }
}

关于java - JPanel:实现我自己的 PaintComponent() 和渲染子项都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2752593/

相关文章:

java - IBM MobileFirst 8 Java 适配器不接受正文中包含数组的 json

Java 键绑定(bind)在按键时输出到控制台

java - 如何在 jframe 标题栏上显示当前日期?

java - 2D 按钮数组 ActionListener,颜色变化?

java - 在 JPanel 中的任意位置添加按钮

java - 在悬停/单击 JMenuItem 时重新绘制 JPanel

java - Jaspersoft Studio - net.sf.jasperreports.engine.JRException : java. lang.ClassNotFoundException : org. hibernate.cfg.Configuration

java - Dialogflow v2 Java 客户端库使用 Spring Boot 检测 Intent : No DesignTimeAgent found for project

java - 如何让鼠标移动在 JPanel 内的多个不同 ImageIcons 上正常工作?

java - 为什么如果我们重写 Finalize 方法可以增加分配阶段?