100个随机圆圈

时间:2014-02-26 20:37:46

标签: java swing jpanel

在我编译完之前的代码后,它工作但现在我不能让圆圈的圆周变成圆圈内的不同颜色。任何建议。

    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        Dimension d = getSize();
        for(int i = 0; i < 100; ++i) 
        {                        
            Color color = new Color(generator.nextInt(255), generator.nextInt(255), generator.nextInt(255));
            g.setColor(color);

            int circleSize = generator.nextInt(d.width / 4);
            int x = generator.nextInt(d.width - circleSize);
            int y = generator.nextInt(d.height - circleSize);
            g.fillOval(x, y, circleSize, circleSize);

            color = new Color(generator.nextInt(255), generator.nextInt(255), generator.nextInt(255));
            g.setColor(color);              
            g.drawArc(x, y, circleSize, circleSize, 0, 360);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

在打包框架之前,只需添加frame.setPreferredSize(new Dimension (700,500));即可。这两种方法旨在结合使用。另外,在设置大小之后移动添加JPanel,这样可以提高代码的可读性,如果考虑语句的顺序,则更有意义。

public static void main (String[] args)
{
JFrame frame = new JFrame ("CircleFrame");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

CircleFramePanel panel = new CircleFramePanel();

frame.setPreferredSize(new Dimension (700,500)); // add it here

frame.pack();

frame.getContentPane().add(panel);  

frame.setVisible(true);
}