Java – why can’t I access my panel’s getWidth () and getHeight () functions?

I'm writing a simple program to test the basic GUI The program prints a letter in the middle of the screen, allowing the user to move it using the arrow keys Everything is fine, but when I try to center the letter at the beginning of the program, it seems that the getWidth and getHeight functions do not return the correct number

This is a fragment 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 functions return '0'?

Thanks for your help

Solution

I can't say why, but:

One way to avoid this is to override your getpreferredsize () function and return your preferred size

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>