Question: Java Help I need the image of that green ship (the player) to be able to move left and right using the arrow keys. I

Java Help

Java Help I need the image of that green ship (the player)

I need the image of that green ship (the player) to be able to move left and right using the arrow keys. I need to do this using KeyListener.

Also when the user lets go of the left or right arrow keys the ship will stop. The variable I use to denote the green ships x coordinate is "xPos".

Here is my code :

InvadersApplication class:

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class InvadersApplication extends JFrame implements Runnable, KeyListener { //member data private static final Dimension WindowSize = new Dimension(600, 600); private static final int NUMALIENS = 30; private Sprite2D[] AliensArray = new Sprite2D[NUMALIENS]; private boolean isInitialised = false; //constructor public InvadersApplication() { //create and set up window this.setTitle("Space Invaders"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); int x = screensize.width / 2 - WindowSize.width / 2; int y = screensize.height / 2 - WindowSize.height / 2; setBounds(x, y, WindowSize.width, WindowSize.height); setVisible(true); for (int i = 0; i  

Sprite2D class:

import javax.swing.*; import java.awt.*; public class Sprite2D { //member data private double x,y; private final Image alienImage; private final Image player; private double xPos = 255; //this is the player ship's x coordinate //constructor public Sprite2D() { ImageIcon icon = new ImageIcon("alien_ship_1.png"); alienImage = icon.getImage(); ImageIcon icon2 = new ImageIcon("player_ship.png"); player = icon2.getImage(); x = Math.random()*600; y = Math.random()*300; } //public interface public void moveEnemy(){ x += 10*(Math.random()-Math.random()); y += 10*(Math.random()-Math.random()); } public void paint(Graphics g){ g.drawImage(alienImage, (int)x, (int)y, null); g.drawImage(player, (int)xPos , 550, null); } } 

Here are the images used:

to be able to move left and right using the arrow keys.

I need to do this using KeyListener. Also when the user lets

Space Invaders

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!