paint()方法的Java程序无故打了两次电话 [英] paint() in java applet is called twice for no reason

查看:167
本文介绍了paint()方法的Java程序无故打了两次电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个共同的原因paint()方法可以在不打算被调用两次。我有以下的code:

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

六角是延伸多边形(以六边形图形模型)的一类,并且DrawHexfromMatrix是绘制从正在绘制的矩阵的索引六边形(放六边形以矩阵的槽)的功能。我可以提供整个code,如果你觉得有帮助,但现在为什么的System.out.println执行两次我不明白。(例如,如果[1] [2] [2] [3 ]不为空,它会打印:

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]的不绘制[K]这也影响了我的画。(矩阵是十六进制的矩阵)。

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

后来编辑:是否有可能以某种方式说g.fill3DRect(我*边,K *,边,边,真正的);到overpaint我试图用hexagon.DrawHexfromMatrix(G,I,K,Color.black)画的六边形; ???

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

推荐答案

首先,你不应该直接画到 JApplet的

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

您应该定义一个的JP​​anel 被添加到 JApplet的。你画到的JP​​anel

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

其次,你应该使用的paintComponent()方法,并调用超类的行为,是这样的。

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

第三,你有秋千的时候触发的paintComponent()方法无法控制。你应该做的计算,在其他一些方法,并限制的paintComponent的code()来实际的绘制方法。

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.

这篇关于paint()方法的Java程序无故打了两次电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆