I am writing a simple program to test the main GUI. The program prints a letter in the middle of the screen and allows the user to move it using the arrow keys. Everything works fine, but when I try to center the letter at the beginning of the program, it seems that the getWidth and getHeight do not return the correct numbers.
Here's a 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 do my getWidth and getHeight return '0'?
Thanks for any help
source share