Java中的绘图面板

时间:2018-03-31 07:34:30

标签: java swing jpanel paint graphics2d

所以我试图同时绘制多个面板。首先,我有一个抽象类,我试图绘制它的实例:

public abstract class GameObject extends JComponent implements ActionListener
{
    public double x;
    public double y;
    public double velX;
    public double velY;
    public Dimension dim;
    public abstract void actionPerformed (ActionEvent e);
}

然后孩子:

public class Ball extends GameObject implements ActionListener
{
    public final double DEF_X = 0;
    public final double DEF_Y = 0;
    public final double DEFAULT_SIZE = 20;

    public Timer t = new Timer(5, this);

    public Ball (int aVelocity)
    {
        x = DEF_X;
        y = DEF_Y;
        velX = aVelocity;
        velY = aVelocity;
        dim = new Dimension((int) DEFAULT_SIZE, (int) DEFAULT_SIZE);

        t.start();
    }

    public void paintComponent (Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D circle = new Ellipse2D.Double(x, y, dim.getWidth(), dim.getHeight());
        g2.fill(circle);
    }

    public void actionPerformed (ActionEvent e)
    {
        if (x < 0 || x > 560)
        {
            velX = -velX;
        }
        if (y < 0 || y > 360)
        {
            velY = -velY;
        }

        x += velX;
        y += velY;

        repaint();
    }
}

所以在驱动程序中我希望2个Ball实例同时移动。在制作了两个球后,我尝试将两者都添加到JFrame中,但只有一个会画画。我尝试将两个球添加到主JPanel p中,然后将p添加到我的JFrame中,但这并没有绘制其中任何一个。

public class Game
{
    public static void main(String[] args)
    {
        JFrame f = new JFrame();
        JPanel p = new JPanel();
        Ball b1 = new Ball(5);
        Ball b2 = new Ball(10);

        p.add(b1);
        p.add(b2);
        f.add(p);
        // I also tried just doing f.add(b1) and f.add(b2), but those only display 1 ball.

        f.setSize(620, 440);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        f.setLocation(dim.width/2-f.getSize().width/2, dim.height/2-f.getSize().height/2);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        f.setVisible(true);
    }
}

那么我该怎样做才能解决这个问题并同时涂上两个球呢?

0 个答案:

没有答案