JPanel中的多个组件不显示

Multiple components in JPanel not displayed

我尝试了很多解决方案,但我不知道我的代码有什么问题。 基本上我想在 window 中显示形状,FlowLayout 不显示任何内容,而 BorderLayout 显示最后一个不是我想要的。忽略 shape.draw() 方法,它只打印形状的坐标。形状扩展了 JComponent。

package Shapes;

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

/**
 * Created by Matej on 10/12/2016.
 */

public class TestShapes extends JFrame
{
    //static Shape[] shapes = new Shape[3];
    public static void main(String[] args)
    {
        Shape[] shapes = new Shape[3];
        shapes[0] = new Circle(300,100,20);
        shapes[1] = new Rectangle(100,100,40,60);
        shapes[2] = new RedRectangle(200,200,20,30);

        TestShapes window = new TestShapes();

        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(500,500);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        for(Shape shape:shapes)
        {
            shape.printName();
            shape.draw();
            panel.add(shape);
        }

        window.add(panel);
        window.setVisible(true);

    }

    public void paint (Graphics g)
    {
        super.paint(g);
    }
}

您没有向我们展示您的 Shape class 和 subclass 的代码,但不管您是否做错了,解决方法是 没有它们扩展了 JComponent。而是让它们 logical 而不是 component classes,然后将它们传递到 JPanel 中,将它们保存在 ArrayList<...> 和在其 paintComponent 方法覆盖中绘制它们。然后将此 JPanel 添加到 JFrame 的 contentPane,BorderLayout.CENTER,以便它可以显示其包含的形状。

请注意,JComponents 的默认首选大小为 0,0,除非有其他理由不这样做——例如,如果它们包含具有首选大小的组件,或者它们具有覆盖的 getPreferredSize() 方法.

但这同样没有实际意义,因为您不想在其自己的组件中显示每个图,因为这会不必要地限制您可以对图像执行的操作以及可以显示它们的位置。