简体   繁体   English

在JPanel上绘图

[英]Drawing on a JPanel

I'm start with create RubicPanel class extended from JPanel from NetbeanIDE set it to black background, put it on a JFrame and I start to draw on it by using another class like this. 我首先从NetBeanIDE的JPanel扩展创建create 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);
   }
}

and result is appear very short time and seem to be replace with black background immediately. 结果出现的时间很短,似乎立即被黑色背景所取代。

how can i fix it and why this problem happened? 我该如何解决?为什么会发生此问题?

and the last thing sorry for my bad English. 最后一件事是我的英语不好对不起。 :) :)

To perform custom painting, override paintComponent . 要执行自定义绘画,请重写paintComponent And since you don't want to clobber the passed Graphics object, it's best that you make a copy that will you later dispose of. 而且由于您不想破坏传递的Graphics对象,因此最好制作一个副本,以备日后使用。 For instance, 例如,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM