【问题标题】:Drawing on a JPanel在 JPanel 上绘图
【发布时间】:2011-12-02 12:07:11
【问题描述】:

我首先从 NetbeanIDE 的 JPanel 扩展创建 RubicPanel 类,将其设置为黑色背景,将其放在 JFrame 上,然后我开始使用像这样的另一个类来绘制它。

public class Drow {
  private final int SquareSize = 99;

  public void DrowRubic(RubicEntity GameRubic, RubicPanel rPanel) {

    Graphics g = rPanel.getGraphics();

          g.setColor(Color.pink);
          g.fillRect(0, 0, 301, 301);
          int CurrentFace = GameRubic.getDirection(1);

          for(int i=0; i<3; i++) {
              for(int j=0; j<3; j++) {
                DrowSquare(g, (99*i)+1 , (j*99)+1, GameRubic.getSpecificCell(i, j, CurrentFace));
              }
          }

       Toolkit.getDefaultToolkit().sync();
       g.dispose();
   }

   public void DrowSquare(Graphics g, int x, int y, Color c) {
       g.setColor(c);
       g.fillRect(x, y, this.SquareSize-1, this.SquareSize-1);
   }
}

结果显示时间很短,似乎立即被黑色背景替换。

我该如何解决?为什么会出现这个问题?

最后一件事很抱歉我的英语不好。 :)

【问题讨论】:

  • 请学习 java 命名约定并遵守它们....不要使用 getGraphics,而是参见 @kirillic 答案
  • This 可能会对您有所帮助。

标签: java swing jpanel java-2d graphic


【解决方案1】:

要执行自定义绘制,请覆盖 paintComponent。而且由于您不想破坏传递的Graphics 对象,因此最好制作一个副本,以便以后处理。例如,

@Override
protected void paintComponent(Graphics g){
    // Get copy
    Graphics gCopy = g.create();
    // Draw on copy
    ...
    // Dispose of copy
    gCopy.dispose();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多