Ok so I am trying to make a galaga game and I'm not getting very far at all. I just tried to make a rectangle be the spaceship and have you able to move it left and right, but it won't work. I added a keylistener and told it to add 5 to x when right arrowkey is hit and subtract 5 from x when the left arrow key is hit but the rectangle doesn't move when I run this program! Here is my code of what I did:
package galaga; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; public class mainmethod extends JFrame{ int x = 200, y= 300; KL bob = new KL(); public mainmethod() { super("Galaga"); setVisible(true); setLocation(150,150); setSize(400,400); addKeyListener(bob); } public class KL implements KeyListener{ public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_LEFT) { x = x-5; } if(e.getKeyCode() == KeyEvent.VK_RIGHT) { x = x+5; } } public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } public void paint(Graphics g) { Image dbImage = createImage(getWidth(), getHeight()); Graphics dbGraphics = dbImage.getGraphics(); paintComponent(dbGraphics); g.drawImage(dbImage, 0, 0, this); } public void paintComponent(Graphics g){ g.setColor(Color.CYAN); Rectangle blarp = new Rectangle(x, y, 150, 150); g.fillRect((int) blarp.getX(), (int) blarp.getY(), 90, 50); } }
Please help me and thanks if you take the time to read this