for循环中出现意外的绘制顺序

时间:2014-11-17 18:25:00

标签: java swing loops

有谁可以帮我弄清楚为什么我的圆圈不会在广场顶部一直打印到顶部?方块看起来很好地打印到框架上,但是我已经无法弄清楚为什么循环在第二排之后停止但从未完成到第六排。谢谢你们!

这是我的主要ExampleGUI.java课程

import javax.swing.*;

public class ExampleGUI {
    public static void main(String args[]) {


        JFrame frame = new JFrame("Example Graphics");
        ExamplePanel panel = new ExamplePanel();

        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(3);
        frame.pack();
        frame.setVisible(true);

    }
}

这是我的方法/构造函数类ExamplePanel.java

import java.awt.*;
import javax.swing.*;

public class ExamplePanel extends JPanel {

    public ExamplePanel() {
        setPreferredSize(new Dimension(600, 600));
    }

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


        int x = 0;
        int x2 = 5;
        int y = 500;
        int y2 = 505;
        int w = 100;
        int w2 = 90;
        int h = 100;
        int h2 = 90;
        int i, j;

        for (j = 1; j < 7; j++) {
            x = 0;
            x2 = x + 5;
            System.out.println(x + " " + y);
            for (i = 1; i < 7; i++) {
                g.setColor(Color.red);
                g.fillRect(x, y, w, h);
                g.setColor(Color.black);
                g.drawRect(x, y, w, h);
                g.setColor(Color.green);
                g.fillOval(x2, y2, w2, h2);
                g.setColor(Color.black);
                g.drawOval(x2, y2, w2, h2);

                x = x + w;
                x2 = x2 + w2 + 10;


            }

            x = x + w;
            y2 = 505;

            y = y - h;
            y2 = (y2 - h2) - 10;
        }


    }
}

1 个答案:

答案 0 :(得分:4)

您必须删除y2= 505; 您错误地将y2设置为每次迭代的相同值:)