绘制多个移动图形

问题描述 投票:2回答:1

我已经使这个程序能够绘制一个使用这两个类在屏幕上弹跳的小球的实例

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JPanel;
import javax.swing.Timer;

public class move extends JPanel implements ActionListener
{
    Timer t = new Timer(7, this);
    int x = 10, y = 10, velX = 7, velY = 7;

    public void paintComponent(Graphics g, Graphics h)
    {
        super.paintComponent(h);
        super.paintComponent(g);
        System.out.println(g);
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
        g2.fill(circle);
        t.start();
    }

    public void actionPerformed(ActionEvent e) {
        if(x<0 || x > getWidth())
        {
            velX = -velX;
        }
        if(y < 0 || y > getHeight())
        {
            velY = -velY;
        }
        x += velX;
        y += velY;
        repaint();
    }   
}

这个类只是简单地绘制球并为计时器等提供逻辑

import java.awt.Color;
import javax.swing.JFrame;

public class Gui {

    public static void main(String[] args)
    {
        move s = new move();
        JFrame f = new JFrame("move");
        f.add(s);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(1000, 1000);
        f.setTitle("Moving Circle");
        f.setBackground(Color.GREEN);
    }
}

下一课只是将它全部放在JFrame中,这是我所知道的非常简单的东西,但我只是想在同一个JFrame中绘制多个实例。我只是想尝试我的代码知识,一些代码实现的样本会很棒。

如何绘制多个移动图形?

java swing graphics java-2d
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.