repaint()在循环中只调用一次 - Java

时间:2016-02-11 19:48:49

标签: java swing

我正在尝试在JPanel上绘制网格,但是当我在循环内调用重绘方法时,它只能运行一次。这是我的代码:

<script>
    var newport = <?php echo (!empty($emparray)) ? @json_encode($emparray) : '[]'; ?>;
</script>

这是输出:

public class Board extends JPanel{

    // --- Set Density of Grid ---
    public final int lines = 10;
    // ---------------------------

    public final int width =  600;
    public final int height = 600;

    public Point p1 = new Point(0,0);
    public Point p2 = new Point(0,0);

    public Board() {


        int c0 = width/lines;
        for (int j=0; j<2; j++){
            int c1 = width/lines;
            for (int i=0; i<lines; i++){

                if (j==0){
                    p1 = new Point(c1,0);
                    p2 = new Point(c1,height);
                }

                if (j==1){
                    p1 = new Point(0,c1);
                    p2 = new Point(width,c1);
                }

                c1 = c1 + c0;

                repaint();

            }
        }
    }


    public void drawGrid(Graphics g){
        g.drawLine(p1.x, p1.y, p2.x, p2.y);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);

        drawGrid(g);
        System.out.println("Inside");
    }

}

当我使用for循环时,如何多次调用paintComponent方法?

1 个答案:

答案 0 :(得分:5)

repaint()方法只是向RepaintManager请求绘制组件。然后RepaintManager将多个请求合并到一个组件绘画中,以使绘画更有效。因此,因为您的所有请求都是在循环中彼此在纳秒内完成的,所以它们都会合并到一个请求中。

如果您想要某种动画,那么您需要使用Swing Timer来安排动画。因此,每次Timer触发时,您都会将索引增加一个。