java小程序中的paint()无故被调用两次
是否有一个常见原因导致 Paint() 方法可能会在无意中被调用两次。我有以下代码:
public void paint(Graphics g)
{
//Graphics2D gg;
//gg=(Graphics2D) g;
drawMatrix(g);
}
private void drawMatrix(Graphics g) {
int side = 40;
hex hexagon=new hex();
for(int i = 0; i<9; i++)
for(int k = 0; k<9; k++){
g.setColor(Color.lightGray);
g.fill3DRect(i*side,k*side, side, side, true);
if (matrix[i][k]!=null){System.out.println("i is "+i+" k is "+k);
g.setColor(Color.black);hexagon.DrawHexfromMatrix(g, i, k, Color.black);}
}
}
hex 是一个扩展多边形的类(以建模六边形图形),而 DrawHexfromMatrix 是一个从所绘制矩阵的索引绘制六边形的函数(将六边形放入矩阵的槽中) )。如果您认为有帮助,我可以提供整个代码,但现在我不明白为什么 system.out.println 被执行两次。(例如 if[1][2] 和 [2][3] 不是null 它将打印:
i is 1 k is 2
i is 2 k is 3
i is 1 k is 2
i is 2 k is 3
我认为这也会影响我的绘图,因为有时虽然 [i][k] 处存在一个元素但未绘制。(矩阵是十六进制矩阵)。
稍后编辑:是否有可能 g. fill3DRect(i*边,k*边, side, side, true); 覆盖我试图用 hexagon.DrawHexfromMatrix(g, i, k, Color.black); 绘制的六边形
Is there a common reason why the paint() method may be called twice without being intended. I have the following code:
public void paint(Graphics g)
{
//Graphics2D gg;
//gg=(Graphics2D) g;
drawMatrix(g);
}
private void drawMatrix(Graphics g) {
int side = 40;
hex hexagon=new hex();
for(int i = 0; i<9; i++)
for(int k = 0; k<9; k++){
g.setColor(Color.lightGray);
g.fill3DRect(i*side,k*side, side, side, true);
if (matrix[i][k]!=null){System.out.println("i is "+i+" k is "+k);
g.setColor(Color.black);hexagon.DrawHexfromMatrix(g, i, k, Color.black);}
}
}
hex is a class that extends polygon (to model a hexagon figure), and the DrawHexfromMatrix is a function that draws a hexagon from the index of the matrix that is drawn(put the hexagon in the slot of a matrix). I can provide the whole code if you think it helps, but for now i don't understand why the system.out.println is executed twice.( for example if[1][2] and [2][3] are not null it will print:
i is 1 k is 2
i is 2 k is 3
i is 1 k is 2
i is 2 k is 3
I think this also affects my drawing because sometimes although an element exists at [i][k] is isn't drawn.(matrix is a matrix of hex).
Later edit: Is it possible somehow that g.fill3DRect(i*side,k*side, side, side, true); to overpaint the hexagons i'm trying to paint with hexagon.DrawHexfromMatrix(g, i, k, Color.black);???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您不应该直接在
JApplet
上绘制。您应该定义一个添加到
JApplet
的JPanel
。您可以在JPanel
上进行绘制。其次,您应该使用
paintComponent()
方法,并调用超类行为,如下所示。第三,您无法控制 Swing 何时触发
paintComponent()
方法。您应该使用其他方法进行计算,并将paintComponent()
中的代码限制为实际的绘图方法。First of all, you should not paint directly to a
JApplet
.You should define a
JPanel
that is added to theJApplet
. You paint to theJPanel
.Second, you should use the
paintComponent()
method, and call the super class behavior, like this.Third, you have no control over when Swing fires the
paintComponent()
method. You should do the calculations in some other method, and limit the code inpaintComponent()
to actual drawing methods.