我只想制作一个简单的水族箱类型的应用程序。鱼从左向右移动。 (鱼的嘴朝右)。当它到达JFrame的末尾时,它返回。我想要的是它必须在它返回时面向左边。(返回)因此,当鱼到达特定坐标时,我决定用新图像绘画。怎么做?请。 图像1 =嘴巴正对的图像鱼 图像2 =嘴巴左侧的图像鱼
package aquarium;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.Random;
import javax.swing.Timer;
public class Aquarium extends JPanel implements ActionListener{
Random r = new Random();
Timer t = new Timer(5, this);
int x = 0, y= 30;
int velX = 1 ,velY =1;
ImageIcon image = new ImageIcon(getClass().getResource("../res/aquarium.gif"));
ImageIcon image1 = new ImageIcon(getClass().getResource("../res/smallFish.gif"));
ImageIcon image2 = new ImageIcon(getClass().getResource("../res/new.gif"));
int numberFish = 12;
Aquarium() {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
image.paintIcon(this, g, 0, 0);
image1.paintIcon(this, g, x, y);
t.start();
}
@Override
public void actionPerformed(ActionEvent e){
Graphics g = null;
if(x<0 || x>465) {
velX = -velX;
}
x += velX;
repaint();
}
public static void main(String[] args) {
Aquarium a = new Aquarium();
JFrame f = new JFrame();
f.setTitle("The Aquarium");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setResizable(false);
f.setBounds(500,200,500,300); //left,top,width,height
f.add(a);
}
}
答案 0 :(得分:0)
使用velX
检查它是哪条鱼并绘制它:
public void paintComponent(Graphics g){
super.paintComponent(g);
image.paintIcon(this, g, 0, 0);
if (velX > 0) { // moving right
image1.paintIcon(this, g, x, y);
} else { // moving left
image2.paintIcon(this, g, x, y);
}
t.start();
}