/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ File: GraphicsExampleFrame3WithKeyboardInput.java Date: 5/22/2006 Author: mr. Hanley Purpose: Demonstrate how to add keyboard interaction @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ import java.awt.*; import javax.swing.*; import javax.imageio.*; //Utilities for working with images import java.awt.image.*; import java.io.*; import java.awt.event.*; public class GraphicsExampleFrame3WithKeyboardInput extends JFrame implements KeyListener { BufferedImage image1; //This is an image variable BufferedImage img = new BufferedImage(500, 400, BufferedImage.TYPE_INT_ARGB); int x = 8, y = 38; int velocity = 4; //how fast plane moves from left to right boolean leftDown, rightDown; //true if left cursor key down and right cursor //key down respectively public void keyPressed(KeyEvent k) { if (k.getKeyCode() == k.VK_RIGHT) { rightDown = true; } if (k.getKeyCode() == k.VK_LEFT) { leftDown = true; } } public void keyTyped(KeyEvent k) {} public void keyReleased(KeyEvent k) { if (k.getKeyCode() == k.VK_RIGHT) { rightDown = false; } if (k.getKeyCode() == k.VK_LEFT) { leftDown = false; } } /***************************************************************** * public GraphicsExampleFrame2WithLoadingImage() * pre: * post: attempts to load image into variable image1 * *****************************************************************/ public GraphicsExampleFrame3WithKeyboardInput() { try { image1 = ImageIO.read(new File("images/kipper.gif")); } catch (java.io.IOException e) { System.out.println(e); } addKeyListener(this); } public void update(Graphics g) { paint(img.getGraphics()); g.drawImage(img, 0, 0, null); } public void paint(Graphics g) { if (rightDown) if (velocity < 15) velocity++; if (leftDown) if (velocity >= 1) velocity--; g.fillRect(0, 0, 500, 400); x += velocity; //draw the image g.drawImage(image1, x, y, null); //Draw the image to the screen g.drawImage(img, 0, 0, null); if(x>=500) x=0; //Pause try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //Invoke repaint repaint(); } }