我刚开始学习Java,最近学习了Timer类。我正在尝试将我学到的东西应用到这个项目中,在这个项目中,一个“太空飞船”会发射“子弹”。我已经让所有的控件都能工作了,但是我在创建另一个子弹对象时,之前的“子弹”会停在中途。我从昨天就一直在搜索,但似乎找不到正确的关键词。我认为我明白为什么会停下来,但是我该如何让子弹继续移动呢?
我在我的JFrame中添加了这个GamePanel类。
我在我的JFrame中添加了这个GamePanel类。
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GamePanel extends JPanel implements KeyListener, ActionListener {
int panelWidth = 500;
int panelHeight = 500;
JLabel spaceship;
int shipWidth = 50;
int shipHeight = 50;
int shipX = 0;
int shipY = panelHeight - shipHeight; // BOTTOM of GamePanel
int shipXVelocity = 5;
JLabel bullet;
int bulletWidth = 10;
int bulletHeight = 25;
int bulletX;
int bulletY;
int bulleyYVelocity = 7;
boolean left,right = false;
Timer timer;
GamePanel() {
timer = new Timer(10,this);
timer.start();
this.setPreferredSize(new Dimension(panelWidth,panelHeight));
this.setLayout(null);
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(this);
spaceship = new JLabel();
spaceship.setBounds(shipX, shipY, shipWidth, shipHeight);
spaceship.setBackground(Color.green);
spaceship.setOpaque(true);
this.add(spaceship);
}
void shoot() {
bulletX = shipX + (shipWidth / 2) - (bulletWidth / 2); // CENTER-TOP of spaceship
bulletY = shipY;
bullet = new JLabel();
bullet.setBounds(bulletX, bulletY, bulletWidth, bulletHeight);
bullet.setBackground(Color.white);
bullet.setOpaque(true);
this.add(bullet);
}
@Override
public void keyTyped(KeyEvent e) {
switch(e.getKeyChar()) {
case 'a' : left = true;
break;
case 'd' : right = true;
break;
}
}
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case 10 : shoot();
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyChar()) {
case 'a' : left = false;
break;
case 'd' : right = false;
break;
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(left == true && shipX > 0) shipX -= shipXVelocity;
if(right == true && shipX < panelWidth - shipWidth) shipX += shipXVelocity;
spaceship.setLocation(shipX, shipY);
if(bullet != null) { // Move if a bullet exist
bulletY -= bulleyYVelocity;
bullet.setLocation(bulletX, bulletY);
}
if(bulletY < 0) this.remove(bullet);;
}
}
输出: