【问题标题】:Add multiple Polygon objects on the same JPanel frame在同一个 JPanel 框架上添加多个 Polygon 对象
【发布时间】:2023-04-03 03:51:01
【问题描述】:

所以我有一个 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 是我为星形颜色实现的函数)。我怎样才能将它们一直添加到框架上? 还有一件事,即使我将框架的背景颜色设置为黑色,在绘制星星后它也会变为灰色。

谢谢!

【问题讨论】:

    标签: java jpanel polygon


    【解决方案1】:

    我重现您的问题。这是Layout 问题。默认情况下,JFrame 具有 BorderLayoutCENTER 对齐。您应该更改布局和屏幕尺寸。

    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)。但这不是最佳解决方案。您应该使用getWidth()getHeight() 方法动态获取与屏幕大小对应的xy

    【讨论】:

    • 似乎可以工作,但如果我添加第三个,它会显示一半。
    • @ChristosS,因为,您在 polycom 上使用了固定像素。您应该根据屏幕尺寸提供像素。还要照顾布局管理器。
    • 为什么?它不会超出框架。它可能在中间,但仍然是一半。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多