Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...