====== Shooting Example ======
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.*;
import java.awt.event.*;
import javax.swing.Timer;
public class ShootingTester extends JPanel implements KeyListener, ActionListener
{
public static int WIDTH=800;
public static int HEIGHT=600;
private Font titleFont, regularFont;
private int keyCode, x, y;
private char c;
private ArrayList bullets;
private Timer timer;
public ShootingTester()
{
//initialize variables here...
titleFont = new Font("Roman", Font.BOLD, 18);
regularFont = new Font("Helvetica", Font.PLAIN, 12);
keyCode=0;
c='-';
x=75;
y=550;
bullets = new ArrayList();
timer = new Timer(20, this); //1000=1 seconds
//timer2 = new Timer(2000, this); //1000=1 seconds
timer.start();
}
public static void main(String[] args) {
ShootingTester app= new ShootingTester();
JFrame window = new JFrame("Type a Key to See Its Code");
window.setSize(WIDTH, HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(app);
window.addKeyListener(app);
//window.pack();
window.setVisible(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(),getHeight());
g.setColor(Color.BLUE);
g.setFont(titleFont);
g.drawString("Type a Key to See Its Code", 20, 20);
g.setColor(Color.BLACK);
g.setFont(regularFont);
g.drawString("Version 1.0", 20, 40);
g.drawString("the key char "+c+" has code "+keyCode, 20, 60);
g.setFont(new Font("Arial", Font.PLAIN, 48));
g.setColor(Color.red);
g.drawString("\""+c+"\"",80, 120);
g.setColor(Color.BLACK);
g.fillRect(x,y, 20, 40);
int i =0;
while(i < bullets.size() ){
bullets.get(i).draw(g);
if (bullets.get(i).getY() < 0)
bullets.remove(i);
else
i++;
}
}
// update is a workaround to cure Windows screen flicker problem
public void update(Graphics g){
paint(g);
}
// These 3 methods need to be declares to implement the KeyListener Interface
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e)
{
keyCode=e.getKeyCode();
c=e.getKeyChar();
int delta = 5;
if(keyCode == 37){
//left
x-=delta;
} else if (keyCode ==38){
// up
y -= delta;
} else if (keyCode ==39){
// right
x += delta;
}else if (keyCode ==40){
// down
y += delta;
} else if (keyCode ==32)
{
//space bar is fire
bullets.add(new Bullet(x+10,y));
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
import java.awt.*;
public class Bullet
{
// instance variables - replace the example below with your own
private int x,y;
/**
* Constructor for objects of class bulliet
*/
public Bullet(int x0, int y0)
{
x = x0;
y = y0;
}
public int getY(){
return y;
}
public void draw(Graphics g)
{
// put your code here
g.setColor(Color.RED);
g.fillRect(x,y,3,8);
y -= 4;
}
}