So for my computer science class we are required to make a video game. I've made a game using an Applet, and it runs properly. Problem is, the KeyListener and the ActionListener won't cooperate. The button will work, but the arrow keys moving the sprite will not. I tried making a seperate class for the button and the game, but they won't work together either. Is there any way around this?
import java.awt.*; import java.applet.*; import java.awt.event.*; import java.awt.Button; import java.net.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class VideoGameProject extends Applet implements Runnable, KeyListener, ActionListener { Button battle; Image background; Image frontview; int dx, dy; int xpos, ypos; int random; int xCoord, yCoord; Thread runner; public void init() { battle = new Button("Look for Pokemon"); battle.addActionListener(this); add(battle); background = getImage(getDocumentBase(),"BACKGROUND.png"); frontview = getImage(getDocumentBase(),"frontview.png"); addKeyListener(this); add (battle); } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { if (runner != null) { runner.stop(); runner = null; } } public void run() { setBackground(new Color(102,197,153)); while(true) { repaint(); xpos+=dx; ypos+=dy; if (xpos>getWidth()-30 || xpos<0) dx*=0; if (ypos>getHeight()-30 || ypos<0) dy*=0; try {Thread.sleep(100);} catch(InterruptedException e) { } } } public void paint(Graphics g) { this.setSize(370, 540); g.drawImage(background,0,0,this); g.drawImage(frontview, xpos, ypos, this); g.setColor(Color.gray); g.fillRect(45,40,60,20); g.fillRect(65,20,20,60); g.setColor(new Color(200,30,26)); g.fillOval(260,50,30,30); g.fillOval(300,30,30,30); g.setColor(Color.white); g.drawString("A",271,70); g.drawString("B",310,50); if(xCoord >500 && yCoord >150 && xCoord <530 && yCoord<200) { g.drawImage(background,0,0,this); } } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { dx = -10; } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { dx = 10; } else if (e.getKeyCode() == KeyEvent.VK_UP) { dy = -10; } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { dy = 10; } repaint( ); } public void keyReleased(KeyEvent e) { dx = 0; dy = 0; } public void keyTyped(KeyEvent e) {} public void actionPerformed(ActionEvent e) { System.out.println("Placeholder"); } }
I'm really desperate for help; my teacher doesn't know how to use the ActionListener and all the chat groups require pay, and I don't have any money. Any help is greatly appreciated, thanks!