在JPanel上绘图 [英] Drawing on a JPanel
问题描述
我首先从NetbeanIDE的JPanel
扩展创建create RubicPanel
类,将其设置为黑色背景,将其放置在JFrame
上,然后开始使用类似这样的其他类来绘制它.
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. :)
推荐答案
要执行自定义绘制,请覆盖paintComponent
.而且,由于您不想破坏传递的Graphics
对象,因此最好制作一个副本,以备日后使用.例如,
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();
}
这篇关于在JPanel上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!