KeyListener not working....
Hi, I am trying to work out how to use the keylistener to make a character move in the tiled map........(both the java files compile fine but the keylistener is not working)
This is my code for GFrame.java that is calling the GMap.java...
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GFrame extends JFrame implements KeyListener
{
static Container c ;
static JPanel gamearea = new JPanel();
static GMap gmap = new GMap();
static JFrame f = new GFrame();
public GFrame()
{
gamearea.add(gmap);
c = getContentPane();
c.setLayout(new BorderLayout());
c.add(gamearea, BorderLayout.CENTER);
c.setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Pirate Game");
pack();
setVisible(true);
setFocusable(true);
gamearea.addKeyListener(this);
addKeyListener(this);
}
public static void main(String args [])
{
f.setVisible(true);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_UP) {
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
}
}
public void keyReleased(KeyEvent e)
{}
}
-
GMap.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GMap extends JPanel
{
int width = 15;
int height =6;
int across,vert;
int x=32;
int y=0;
int keyCode;
String keyString;
int[][] A = {{1,2,1,1,1,1,1,1,1,1,1,1,1,2,1},
{1,2,1,1,1,1,1,1,1,1,1,1,1,2,1},
{1,2,1,1,1,1,1,1,1,1,1,1,1,2,1},
{1,2,1,1,1,1,1,1,1,1,1,1,1,2,1},
{1,2,2,2,2,2,2,2,2,2,2,2,2,2,1},
{1,3,3,3,3,3,3,3,3,3,3,3,3,3,1},
};
Image stone = Toolkit.getDefaultToolkit().getImage("stone.PNG");
Image grass = Toolkit.getDefaultToolkit().getImage("grass.PNG");
Image wall = Toolkit.getDefaultToolkit().getImage("wall.PNG");
Image pirate = Toolkit.getDefaultToolkit().getImage("pirate.PNG");
public GMap()
{
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(448, 448));
//this.addKeyListener(this);
// this.setFocusable(true);// Allow panel to get focus
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
for(across = 0; across < width ; across++)
{
for(vert = 0; vert < height ; vert++)
{
if (A[vert][across] == 1)
{
g2.drawImage(stone,across*32,vert*32,this);
}
else if(A[vert][across]==2)
{
g2.drawImage(grass,across*32,vert*32,this);
}
else
{
g2.drawImage(wall,across*32,vert*32,this);
}
}
}
g.drawImage(pirate, x, y,this);
}
public void move()
{
y+=10;
repaint();
}
}
--
Can anybody spot what the mistake? Thanks...I really need the answer...

