0

这是我的代码。我有 4 个类,一个抽象类 (GeoShape),一个扩展 GeoShape 的 Rectangle 类,一个包含我的 GeoShape 并尝试绘制它们的 GraphicsPanel,以及一个 Launcher 类。

GeoShape.java

public abstract class GeoShape
{
    protected Point p;
    protected int width, height;

    public GeoShape(Point p, int width, int height)
    {
        this.p = p;
        this.width = width;
        this.height = height;
    }

    public void drawItself(Graphics g)
    {
        g.setColor(Color.BLACK);
    }

    // Getters and setters...
}   

矩形.java

public class Rectangle extends GeoShape
{
    public Rectangle(Point p, int width, int height)
    {
        super(p, width, height);    
    }

    @Override
    public void drawItself(Graphics g)
    {
        super.drawItself(g);
        g.drawRect((int)p.getX(), (int)p.getY(), width, height);
    }
}

图形面板.java

public class GraphicsPanel extends JPanel
{
    private static final long serialVersionUID = 1L;
    private ArrayList<GeoShape> list;

    public GraphicsPanel() 
    {
        list = new ArrayList<GeoShape>();
    }

    @Override
    public void paintComponents(Graphics g) 
    {
        super.paintComponents(g);
        for(int i = 0 ; i < list.size() ; i++) list.get(i).drawItself(g);
    }

    public void addShapeInList(GeoShape s)
    {
        list.add(s);
    }
}

启动器.java

public class Launcher extends JFrame
{
    private static final long serialVersionUID = 1L;
    private GraphicsPanel panel;

    public Launcher()
    {
        panel = new GraphicsPanel();
        panel.addShapeInList(new Rectangle(new Point(3,9),120,20));
        panel.repaint();

        this.setTitle("Test");
        this.setContentPane(panel);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(700, 500);
        this.setVisible(true);
    }

    public static void main(String[] args) 
    {
        new Launcher();
    }
}

框架中没有任何反应......感谢您的帮助。

4

1 回答 1

2

尝试将其替换为paintComponent而不是paintComponents

public void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    for(int i = 0 ; i < list.size() ; i++) list.get(i).drawItself(g);
}
于 2013-01-23T11:02:35.970 回答