为什么我不能访问我的面板的getWidth()和getHeight()函数? [英] Why can't I access my panel's getWidth() and getHeight() functions?
问题描述
我正在编写一个简单的程序来测试基本的GUI。程序在屏幕中间打印一个字母,允许用户使用箭头键移动它。一切正常,但是当我尝试在程序开头处将字母居中时,似乎 getWidth
和 getHeight
函数没有返回正确的数字。
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.
这是包含我的Panel类的片段
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);
}
}
为什么我的 getWidth
和 getHeight
函数返回'0'?
Why are my getWidth
and getHeight
functions returning '0'?
感谢您的帮助
推荐答案
我说不出原因但是:
避免这种情况的一种方法是覆盖您的 getPreferredSize()
功能并返回您的首选尺寸。
A way to avoid this is to override your getPreferredSize()
function and return your preferred size.
这篇关于为什么我不能访问我的面板的getWidth()和getHeight()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!