Hello, i am trying to add a keyboard event listener to my Jpanel. But i am having no sucess.
This is my board.java
package snake;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.ImageObserver;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import java.awt.Image;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class board extends JPanel implements KeyListener
{
Image body;
Image head;
int WIDTH = 300;
int HEIGHT = 300;
int ALL_DOTS = 900;
int Dot_Size = 10;
int x[] = new int[ALL_DOTS];
int y[] = new int[ALL_DOTS];
int dots;
int sleep = 200;
boolean start = true;
boolean right = true;
boolean left = false;
boolean up = false;
boolean down = false;
public board()
{
setBackground(Color.black);
requestFocus();
addKeyListener(this);
dots = 3;
ImageIcon head_image = new ImageIcon(this.getClass().getResource("reddot.png"));
ImageIcon body_image = new ImageIcon(this.getClass().getResource("greendot.png"));
head = head_image.getImage();
body = body_image.getImage();
start();
}
public void start()
{
for (int z = 0; z < dots; z++) {
x[z] = 50 - z*Dot_Size;
y[z] = 50;
}
}
public void GameOver(Graphics g)
{
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = this.getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg,(150-metr.stringWidth(msg)/2),(300/2));
}
public void collision()
{
if (x[0] > WIDTH)
{
start=false;
}
}
public void paint(Graphics g)
{
if (start)
{
super.paint(g);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(body, x[z], y[z], this);
}
}
try {
Thread.sleep(sleep);
} catch (InterruptedException ex) {
Logger.getLogger(board.class.getName()).log(Level.SEVERE, null, ex);
}
collision();
move();
}
else GameOver(g);
}
public void move()
{
for (int z = dots; z > 0; z--)
{
x[z] = x[(z - 1)];
}
if (right)
{
x[0] += Dot_Size;
}
repaint();
}
public void keyTyped(KeyEvent e) {
System.out.println("Hello");
}
public void keyPressed(KeyEvent e) {
System.out.println("Hello");
}
public void keyReleased(KeyEvent e) {
System.out.println("Hello");
}
}
this is my main.java
package snake;
import java.applet.Applet;
import java.awt.Color;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
add(new board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(320, 340);
setLocationRelativeTo(null);
setTitle("Snake");
setFocusable(true);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}