Question: Modify the Direction program so that the arrows do not run off the screen when the the up/down/left/right arrows are pressed on the keyboard. (also:

Modify the Direction program so that the arrows do not run off the screen when the the up/down/left/right arrows are pressed on the keyboard.

(also: the gif images do not display when i run the code. These images are held in a sperate folder within the same src folder as my code)

Here is my code so far:

import javax.swing.JFrame;

public class event { public static void main(String[] args) {

JFrame frame = new JFrame("Direction");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new direction());

frame.pack();

frame.setVisible(true); } }

----------------------------------------------------------------------------------------------------------------------------------------------------------------

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class direction extends JPanel {

private final int WIDTH = 300,

HEIGHT = 200;

private final int JUMP = 10;

private final int IMAGE_SIZE = 31;

private ImageIcon up, down, right, left, currentImage; private int x, y;

public direction() {

addKeyListener(new DirectionListener());

x = WIDTH / 4;

y = HEIGHT / 4;

up = new ImageIcon("arrowUp.gif");

down = new ImageIcon("arrowDown.gif");

left = new ImageIcon("arrowLeft.gif");

right = new ImageIcon("arrowRight.gif");

currentImage = right; setBackground(Color.black);

setPreferredSize(new Dimension(WIDTH, HEIGHT));

setFocusable(true); }

// Draws the image in the current location

public void paintComponent(Graphics page) {

super.paintComponent(page);

currentImage.paintIcon(this, page, x, y); }

// Represents the listener for the keyboard activity

private class DirectionListener implements KeyListener {

// Responds to the user pressing arrow keys by adjusting the

// image and image location accordingly

public void keyPressed(KeyEvent event) {

switch (event.getKeyCode()) {

case KeyEvent.VK_UP:

currentImage = up;

y -= JUMP;

break;

case KeyEvent.VK_DOWN:

currentImage = down;

y += JUMP;

break;

case KeyEvent.VK_LEFT:

currentImage = left;

x -= JUMP;

break;

case KeyEvent.VK_RIGHT:

currentImage = right;

x += JUMP;

break; }

repaint(); }

// Provide empty definitions for unused event methods

public void keyTyped(KeyEvent event) {}

public void keyReleased(KeyEvent event) {}

} }

ANY HELP IS APPRECIATED

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!