为什么我的所有形状都卡在我的JPanel的左上角?

时间:2016-04-10 20:21:18

标签: java swing user-interface jpanel shapes

我创建了一个充满圆形,线条和矩形的JPanel,它们应该在JPanel周围随机产生,但是圆形和矩形只显示在JPanel的左上角而不是整个JPanel中随机出现,虽然线条运作完美。我想知道是否有人可以帮助我?

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;

/**
 *
 * 
 */
public class RandomShapesPanel extends JPanel
{
    private Color rColor;
    private Random rGen;
    private Random num;

    @Override
    protected void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    int x = this.getWidth();
    int y = getHeight();
    int x1, y1, x2, y2;
    rGen = new Random();
    num = new Random();
    for(int i = 1; i <= 35; i++)
    {
        rColor = new Color(rGen.nextInt(256),rGen.nextInt(256),
                rGen.nextInt(256));
        g.setColor(rColor);
        x1 = rGen.nextInt(x - 1) + 1;
        x2 = rGen.nextInt(x - 1) + 1;
        y1 = rGen.nextInt(y - 1) + 1;
        y2 = rGen.nextInt(y - 1) + 1;
        g.drawLine(x1, y1, x2, y2);
    }
    for(int i = 1; i <= 35; i++)
    {
        rColor = new Color(rGen.nextInt(256),rGen.nextInt(256),
                rGen.nextInt(256));
        g.setColor(rColor);
        x1 = num.nextInt(50) + 10;
        x2 = num.nextInt(50) + 10;
        y1 = num.nextInt(50) + 10;
        y2 = num.nextInt(50) + 10;
        g.drawRect(x1, y1, x2, y2);
    }
    for(int i = 1; i <= 35; i++)
    {
        rColor = new Color(rGen.nextInt(256),rGen.nextInt(256),
                rGen.nextInt(256));
        g.setColor(rColor);
        x1 = num.nextInt(50) + 10;
        x2 = num.nextInt(50) + 10;
        y1 = num.nextInt(50) + 10;
        y2 = num.nextInt(50) + 10;
        g.fillRect(x1, y1, x2, y2);
    }
    for(int i = 1; i <= 35; i++)
    {
        rColor = new Color(rGen.nextInt(256),rGen.nextInt(256),
                rGen.nextInt(256));
        g.setColor(rColor);
        x1 = num.nextInt(50) + 10;
        x2 = num.nextInt(50) + 10;
        y1 = num.nextInt(50) + 10;
        y2 = num.nextInt(50) + 10;
        g.drawOval(x1, y1, x2, y2);
    }
    for(int i = 1; i <= 35; i++)
    {
        rColor = new Color(rGen.nextInt(256),rGen.nextInt(256),
                rGen.nextInt(256));
        g.setColor(rColor);
        x1 = num.nextInt(50) + 10;
        x2 = num.nextInt(50) + 10;
        y1 = num.nextInt(50) + 10;
        y2 = num.nextInt(50) + 10;
        g.fillOval(x1, y1, x2, y2);
    }
    }
}

0 个答案:

没有答案