Original Post
Hey GD community. I've been learning programming for a couple weeks now and I have a problem with keylistener. When I call getKeyChar() it prints out the letter I typed but when I call getKeyCode() it always returns 0. Can anyone find the problem? Also I've seen different bracing styles. Is there one preferred over the other? Any criticism on my coding style is appreciated. I want to start out right.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Core extends JComponent implements KeyListener
{
private Player player = new Player(100, 600);
private Shot shot;
private boolean gameOver = false;
private int level = 1;
private Image img;
public Core()
{
setFocusable(true);
addKeyListener(this);
}
public void nextLevel()
{
level++;
}
public void gameOver()
{
gameOver = true;
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, 800, 700);
img = player.getImage(player.getLevel());
player.update();
g2.drawImage(img, player.getX()-14, player.getY(), this);
for(int i=0; i<player.getNumShots(); i++)
{
shot = player.getShots(i);
if(shot != null)
{
img = shot.getImage(shot.getDamage());
g2.drawImage(img, shot.getX(), shot.getY(), this);
shot.updatePos();
}
}
try{ Thread.sleep(20); }
catch(InterruptedException ie){}
repaint();
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
System.out.println(e.getKeyCode());
System.out.println(e.getKeyChar());
}
}