简体   繁体   English

java applet中的paint()被无故两次调用

[英]paint() in java applet is called twice for no reason

Is there a common reason why the paint() method may be called twice without being intended. 有一个常见的原因为什么paint()方法可能会被无意调用两次。 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). hex是扩展多边形的类(用于建模六边形图形),而DrawHexfromMatrix是从绘制的矩阵索引绘制六边形的函数(将六边形放入矩阵的槽中)。 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: 如果您认为有帮助,我可以提供整个代码,但是现在我不明白为什么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 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). 我认为这也会影响我的绘图,因为有时虽然[i] [k]中存在一个元素,但并未绘制。(矩阵是十六进制的矩阵)。

Later edit: Is it possible somehow that g.fill3DRect(i*side,k*side, side, side, true); 以后的编辑:是否有可能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);??? 覆盖我尝试用hexagon.DrawHexfromMatrix(g,i,k,Color.black)绘制的六边形; ???

First of all, you should not paint directly to a JApplet . 首先,您不应该直接在JApplet绘画。

You should define a JPanel that is added to the JApplet . 您应该定义一个添加到JAppletJPanel You paint to the JPanel . 您可以绘制到JPanel

Second, you should use the paintComponent() method, and call the super class behavior, like this. 其次,您应该使用paintComponent()方法,并调用超级类行为,如下所示。

protected void paintComponent(Graphics g) {
    // Paint the default look.
    super.paintComponent(g);

    // Your custom painting here.
    g.drawImage(foregroundImage, x, y, this);
}

Third, you have no control over when Swing fires the paintComponent() method. 第三,您无法控制Swing何时触发paintComponent()方法。 You should do the calculations in some other method, and limit the code in paintComponent() to actual drawing methods. 您应该使用其他方法进行计算,并将paintComponent()的代码限制为实际的绘制方法。

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

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