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

巧了我就是萌 提交于 2019-11-26 18:39:37

问题


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);???


回答1:


First of all, you should not paint directly to a JApplet.

You should define a JPanel that is added to the JApplet. You paint to the JPanel.

Second, you should use the paintComponent() method, and call the super class behavior, like this.

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. You should do the calculations in some other method, and limit the code in paintComponent() to actual drawing methods.



来源:https://stackoverflow.com/questions/8067844/paint-in-java-applet-is-called-twice-for-no-reason

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