Because of some odd reason, my key listener doesn't work. If you can help me that would be great.
Here is my eclipse workspace: Pong_WORKSPACE.zip
and here are all the class files on their own.
Pong.java (main class)
package net.nivangerow.pong; import javax.swing.*; import java.awt.*; public class Pong { public static void main(String[] args) { JFrame frame = new JFrame("Pong by nivangerow"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(640, 480); frame.add(new Game()); } }
Game.java
package net.nivangerow.pong; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Game extends JPanel implements ActionListener{ Timer time; Image ball; public Bat b3; public Game() { b3=new Bat(); setVisible(true); setSize(640, 480); setBackground(Color.BLACK); time = new Timer(5, this); time.start(); ImageIcon b2 = new ImageIcon(getClass().getResource("ball.png")); ball = b2.getImage(); addKeyListener(new AL()); } public void actionPerformed(ActionEvent e) { //System.out.println(b3.y+" "+b3.py); b3.move(); repaint(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(b3.bat, 0, b3.y, null); } public class AL extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key==KeyEvent.VK_W) { b3.py=-1; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if(key==KeyEvent.VK_W) { b3.py=0; } } } }
Bat.java
package net.nivangerow.pong; import java.awt.*; import javax.swing.ImageIcon; public class Bat { public int y=180; public int py=0; Image bat; public Bat() { ImageIcon b1 = new ImageIcon(getClass().getResource("bat.png")); bat = b1.getImage(); } public void move() { //System.out.println("MOVING"); y = y + py; } }