Just for fun I am trying to make my own version of the old game Crazy Taxi. I am only to the point of having the character however. I am at the stage of trying to make sure the character (goku icon) can move between the three lanes. I have it set up so that when the user presses the right or left arrow keys, the icon will jump from one lane to another, however even though my code was error free, the icon did not move. So I added a label that allowed me to keep track of the x-coordinate of the icon to see if that was even changing when I pressed one of the arrow keys. It does not. Is there an error in my code that is keeping the keyListener from working? Here is my code:
And here is the main method that runs the applet:import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ThreeLanesPanel extends JPanel { private final int WIDTH = 400, HEIGHT = 400; private final int DELAY = 100, GOKU_SIZE = 45; private ImageIcon goku; private Timer timer; private int gokux, gokuy, moveX, moveY, testing; private JLabel label; public ThreeLanesPanel() { timer = new Timer(DELAY, new ThreeLanesListener()); addKeyListener(new GokuListener()); label = new JLabel("Goku's X coordinate: " + gokux); goku = new ImageIcon("Goku.gif"); gokux = 40; gokuy = 355; moveX = moveY = 3; add(label); setPreferredSize(new Dimension(WIDTH,HEIGHT)); setBackground(Color.white); timer.start(); } public void paintComponent(Graphics page) { super.paintComponent(page); goku.paintIcon(this,page,gokux,gokuy); page.drawLine(133,0,133,400); page.drawLine(266,0,266,400); } private class ThreeLanesListener implements ActionListener { public void actionPerformed(ActionEvent event) { } } private class GokuListener implements KeyListener { public void keyPressed (KeyEvent event) { switch (event.getKeyCode()) { case KeyEvent.VK_RIGHT: gokux += 130; testing = 100; break; case KeyEvent.VK_LEFT: gokux -= 130; testing = 150; break; } repaint(); label.setText("Test number: " + testing); } public void keyTyped(KeyEvent event){} public void keyReleased(KeyEvent event) {} } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ThreeLanes { public static void main(String[] args) { JFrame frame = new JFrame("ThreeLanes"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new ThreeLanesPanel()); frame.pack(); frame.setVisible(true); } }