Drawing on a JPanel

核能气质少年 提交于 2019-12-11 00:33:09

问题


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.

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. :)


回答1:


To perform custom painting, override 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. For instance,

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


来源:https://stackoverflow.com/questions/8356111/drawing-on-a-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!