rendered paste bodyimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
import java.io.*;
public class myJPanel extends JPanel implements ActionListener, KeyListener
{
private Timer shotTimer;
private Timer alienTimer;
private int shotDelay=10;
private int alienDelay=100;
//ship coordinates
private int shipX=0;
private int shipY=500;
//shot coordinates
private int shotX=-20;
private int shotY=530;
//alien coordinates
private int alienX=10;
private int alienY=20;
private JButton b;
//Direction of the aliens
private String DirectionMoving="right";
public myJPanel()
{
super();
setBackground(Color.black);
//create the timer.
shotTimer = new Timer(shotDelay, this);
shotTimer.addActionListener(this);
alienTimer = new Timer(alienDelay, this);
alienTimer.addActionListener(this);
alienTimer.start();
setLayout(new BorderLayout());
b = new JButton("");
b.addKeyListener(this);
b.requestFocusInWindow();
//create the new panel, and add the buttons
JPanel colorPanel = new JPanel();
//keys
colorPanel.add(b);
//add to the panel
add(colorPanel, BorderLayout.SOUTH);
}
/*****************
* Paint
*****************/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//draw the ship
try
{
g.drawImage(ImageIO.read(new File("ship.gif")), shipX, shipY, null);
}
catch (Exception e)
{
e.printStackTrace();
}
//draw the shot
g.setColor(Color.red);
g.fillOval(shotX, shotY, 10, 10);
//draw the aliens
try
{
g.drawImage(ImageIO.read(new File("alien.gif")), alienX, alienY, null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/***********************
* Regular Actions
***********************/
public void actionPerformed(ActionEvent event)
{
Object obj = event.getSource();
//shots
if(obj == shotTimer)
{
if (shotY<=0)
{
shotY=600;
repaint();
shotTimer.stop();
}
else
{
shotY-=10;
repaint();
}
}
//aliens
if(obj == alienTimer)
{
if (DirectionMoving.equals("right"))
{
alienX+=10;
if (alienX>=450)
DirectionMoving="left";
}
if (DirectionMoving.equals("left"))
{
alienX-=10;
if(alienX<=5)
DirectionMoving="right";
}
repaint();
}
}
/**********************
* Key Mapping
**********************/
public void keyPressed(KeyEvent e)
{
int x = e.getKeyCode();
//left arrow
if(x == e.VK_LEFT)
{
if (shipX>=10)
shipX-=10;
repaint();
}
//Right arrow
if(x == e.VK_RIGHT)
{
if (shipX<=460)
shipX+=10;
repaint();
}
//Space
if(x == e.VK_SPACE)
{
shotX = shipX;
shotTimer.start();
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
}