java小程序中的paint()被无故调用两次 [英] paint() in java applet is called twice for no reason

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

问题描述

paint() 方法可能会在无意中被调用两次是否有一个常见的原因.我有以下代码:

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 是一个扩展多边形的类(用于模拟六边形图形),而 DrawHexfromMatrix 是一个函数,它根据绘制的矩阵的索引绘制六边形(将六边形放在矩阵的槽中).如果您认为有帮助,我可以提供整个代码,但现在我不明白为什么 system.out.println 被执行两次.(例如 if[1][2] 和 [2][3] 不是null 它将打印:

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(i*side,k*side, side, side, true); 是否有可能为了覆盖我正在尝试用六边形绘制的六边形.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.

您应该定义一个添加到 JAppletJPanel.您绘制到 JPanel.

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

第三,您无法控制 Swing 何时触发 paintComponent() 方法.你应该用其他的方法来计算,把paintComponent()中的代码限制为实际的绘制方法.

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.

这篇关于java小程序中的paint()被无故调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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