如何更改代码以允许椭圆而不是图像移动?
我知道我必须使用图形2D类。。。
我想我得在面板上加上椭圆。。
喜欢
ArrayList<Shape> shapeArray = new ArrayList<Shape>();
public MyPanel(){
Shape s;
s= new Ellipse2D.Float(0, 0, 80, 50);
shapeArray.add(s);
我该怎么做?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
class MyPanel extends JPanel implements ActionListener{
private final int WIDTH = 500;
private final int HEIGHT = 300;
private final int START_X = 0;
private final int START_Y = 250;
private BufferedImage image;
private Timer timer;
private int x, y;
public MyPanel() {
setBackground(Color.BLACK);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setDoubleBuffered(true);
File input = new File("starship.png");
try {
image = ImageIO.read(input);
} catch(IOException e) {
e.printStackTrace();
}
x = START_X;
y = START_Y;
timer = new Timer(20, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, this);
}
@Override
public void actionPerformed(ActionEvent e) {
x+=1;
y-=1;
if(x>WIDTH) {
x=START_X;
y=START_Y;
}
repaint();
}
}
public class MyFrame extends JFrame {
public MyFrame() {
add(new MyPanel());
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
暂无答案!
目前还没有任何答案,快来回答吧!