在同一JPanel框架上添加多个Polygon对象

时间:2013-11-29 11:53:46

标签: java jpanel polygon

所以我有一个DrawStar类,使用Polygon绘制一个星形:

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    int[] cX = new int[] {x, x+5, x+20, x+8, x+16, x, x-16, x-8, x-20, x-5, x};
    int[] cY = new int[] {y, y+14, y+14, y+22, y+39, y+29, y+39, y+22, y+14, y+14, y};
    Polygon pol = new Polygon(cX, cY, 11);
    g2.setColor(this.color);
    g2.draw(pol);
    g2.fillPolygon(pol);
}

然后在我的主课程中,我创建了一个JPanel框架来绘制星星:

    ...
    JFrame starsframe = new JFrame();
    starsframe.setTitle("Random stars...");
    starsframe.setSize(600, 400);
    starsframe.setLocationRelativeTo(null);
    starsframe.setVisible(true);
    starsframe.setResizable(false);
    starsframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DrawStar star1 = new DrawStar(300, 200, CreateColor(color));
    starsframe.add(star1);
    DrawStar star2 = new DrawStar(400, 300, CreateColor(color));
    starsframe.add(star2);
    ...

但是,它只适用于一颗星。如果我添加第二个(如上所述),则不会绘制任何一个(CreateColor是我为星形颜色实现的函数)。如何在框架上添加它们? 还有一件事,即使我将框架的背景颜色设置为黑色,它也会在绘制星星后变为灰色。

谢谢!

1 个答案:

答案 0 :(得分:1)

我重现你的问题。那是Layout问题。默认情况下,JFrame具有BorderLayout CENTER对齐。您应该更改布局和屏幕大小。

JFrame starsframe = new JFrame();
starsframe.setTitle("Random stars...");
starsframe.setLayout(new GridLayout( 1,2));// Use gridLayout
DrawStar star1 = new DrawStar(300, 200, Color.red);
starsframe.add(star1);
DrawStar star2 = new DrawStar(400, 300, Color.blue);
starsframe.add(star2);

starsframe.setSize(1000,700);// Increase the screen size.
starsframe.setLocationRelativeTo(null);
starsframe.setVisible(true);
starsframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

要查看我使用GridLayout(1,2)和更大setSize(1000, 700)的两颗星。但这不是最佳解决方案。您应该使用xy方法动态获取getWidth()getHeight()与屏幕尺寸相对应。