I'm trying to implement a key listener to a program I'm doing for school. I got a little help with it already elsewhere but I'm still having trouble getting it to work. I will include the two classes that should be of importance. I have two others that handle the images and variable data but I don't think they have any effect with the problem at hand.
As you can see the listener is there and I did addKeyListener(this) in the constructer like I was told. When I press any buttons on the keyboard nothing happens. All I really need is to get it to respond to a key stroke and I think I can handle everything else in the program. Everything else is also currently working properly. Any help with what I'm doing wrong would be greatly appreciated. Thank you all very much for your time and have a good day.
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.util.*; import java.util.Timer; public class ArcadeFighterPanel extends JPanel implements KeyListener { //declare variables position xydata = new position(); int playerx = xydata.PlayerX(), playery = xydata.PlayerY(); int delay = 1000; // delay for 1 sec. int period = 1000; // repeat every sec. Timer timer = new Timer(); final int MAX_LEFT_X = 0, MAX_RIGHT_X = 250, MAX_Y = 171; BufferedImage loadImg = ImageControll.makeColorTransparent("fighter_idle.png", Color.WHITE); //set up the panel that displays public ArcadeFighterPanel () { /*JButton changeButton = new JButton ("Start Game"); changeButton.addActionListener(new ChangeListener()); add(changeButton); */ setBackground(Color.GRAY); setPreferredSize(new Dimension(600,250)); addKeyListener(this); } //pant the screen with characters public void paintComponent (Graphics page) { super.paintComponent(page); page.setColor(Color.GREEN); page.fillRect(0, 225, 600, 25); page.drawImage(loadImg, playerx, playery, this); timer.scheduleAtFixedRate(new TimerTask() { public void run() { playerx = xydata.PlayerX(); playery = xydata.PlayerY(); repaint(); } }, delay, period); } @Override public void keyPressed(KeyEvent e) { System.out.println("Key pressed"); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }
import javax.swing.*; public class arcadeFighter { private static JFrame frame; public static void main(String[] args) { JFrame frame = new JFrame ("Awsome Arcade Fighter Extreem"); frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); frame.setResizable( false ); frame.getContentPane().add(new ArcadeFighterPanel()); frame.pack(); frame.setVisible(true); } }