I'm writing a simple program to test out basic GUI. The program prints a letter in the middle of the screen and allows the user to move it with the arrow keys. Everything works fine, but when I try to center the letter at the start of the program, it seems that the getWidth
and getHeight
functions aren't returning the proper numbers.
Here's the snippet containing my Panel class
static class LinePanel extends JPanel{
int xCenter = getWidth() /2;
int yCenter = getHeight() /2;
private int x = xCenter;
private int y = yCenter;
private char keyChar = 'A';
public LinePanel(){
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN: y += 10; break;
case KeyEvent.VK_UP: y -= 10; break;
case KeyEvent.VK_LEFT: x -= 10; break;
case KeyEvent.VK_RIGHT: x += 10; break;
default: keyChar = e.getKeyChar();
}
repaint();
}
});
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setFont(new Font("TimesRoman", Font.PLAIN, 24));
g.drawString(String.valueOf(keyChar), x, y);
}
}
Why are my getWidth
and getHeight
functions returning '0'?
Thanks for any help