public class JLaser extends JPanel implements Runnable {
public JLaser() {
this.setSize(1, 10);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.drawLine(0, 0, 0, 9);
}
public void fire() {
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
@Override
public void run() {
while (this.getY() >= 0) {
this.setLocation(this.getX(), this.getY() - 10);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
}
}
setVisible(false);
this.getParent().remove(this);
}
}
Codice da utilizzare nel Main:
@Override
public void mouseMoved(MouseEvent me) {
pnlAstronave.setLocation(me.getX()-5, pnlAstronave.getY());
}
@Override
public void keyReleased(KeyEvent ke) {
if (ke.getKeyChar()==' ') {
JLaser laser = new JLaser();
laser.setBounds(pnlAstronave.getX()+5, pnlAstronave.getY()-10, 1, 10);
panel.add(laser);
laser.setVisible(true);
laser.fire();
}
}