Drawing on a JPanel

2019-07-19 15:32发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-07-19 15:44

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();
}
查看更多
登录 后发表回答