【问题标题】:JPanel: both implementing my own paintComponent() and rendering children doesn't workJPanel:实现我自己的paintComponent() 和渲染孩子都不起作用
【发布时间】:2010-05-02 06:00:09
【问题描述】:

我正在扩展一个 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
      }
    }
  }
}

【问题讨论】:

  • 对我来说没问题。你用的是什么 JDK 和 L&F?
  • 啊哈!我是个皮洛克! (Pillock 是一个非常有趣的词。)棋盘的每个图块都有自己的绘制方法,问题是我正在翻译 Graphics 对象,以便每个图块可以从 (0,0) 作为左上角进行绘制.而且,愚蠢的我,在绘制其余组件之前,我忘了翻译回全局原点。

标签: java swing jpanel paintcomponent


【解决方案1】:

总的来说,我没有看到任何关于你的代码的愚蠢之处,但我想说你的组件层次结构似乎有点愚蠢。

你没有更好地分离你的对象有什么原因吗?为了保持您的代码可维护和可测试,我鼓励您将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);
  }
}

【讨论】:

  • 当我运行解决方案时,我发现您的方法可以很好地解决它,并且确实更好地分离了代码。请参阅我对以下问题的评论:a) 问题中未实际提及的 真实 问题,以及 b) 我是个小笨蛋。
猜你喜欢
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 2012-09-21
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多