setLocation 不适用于扩展 JPanel 的类 [英] setLocation not working on class extending JPanel
问题描述
我有一个名为Player"的类,它扩展了 JPanel.该类具有属性 x 和 y (这可能是问题,但我无法弄清楚).当我运行下一个代码时,它将 JPanel 的位置设置为 (100, 100):
private void initGamePanel() {gamePanel.setBackground(Color.BLUE);gamePanel.setVisible(true);gamePanel.setLayout(null);JPanel jPanel = new JPanel();jPanel.setLocation(100, 100);jPanel.setSize(100, 100);jPanel.setBackground(Color.CYAN);gamePanel.add(玩家);}
但是当我对 "Player" 类做同样的事情时,位置保持在 (0, 0):
private void initGamePanel() {gamePanel.setBackground(Color.BLUE);gamePanel.setVisible(true);gamePanel.setLayout(null);玩家 = 新玩家();player.setLocation(100, 100);player.setSize(100, 100);player.setBackground(Color.CYAN);gamePanel.add(玩家);}
还有一件事:当我在构造函数中设置玩家的 x 和 y 时,位置等于这些值.
该类具有属性 x 和 y(这可能是问题所在
可能是这样,特别是如果您有 getX()
和 getY()
方法,因为这些方法已经由 JPanel 实现,不应被覆盖.>
不确定是否真的需要 x/y 属性,因为您可以直接设置组件的位置.
如果您出于其他原因需要这些属性,那么它们应该具有更具描述性的名称,以避免与类变量混淆.
I have a class named "Player" which extends JPanel. The class has the attributes x and y (which might be the problem but I can't figure it out). When I run the next code it sets the location of the JPanel to (100, 100):
private void initGamePanel() {
gamePanel.setBackground(Color.BLUE);
gamePanel.setVisible(true);
gamePanel.setLayout(null);
JPanel jPanel = new JPanel();
jPanel.setLocation(100, 100);
jPanel.setSize(100, 100);
jPanel.setBackground(Color.CYAN);
gamePanel.add(player);
}
But when I do the same with the "Player" class, the position stays at (0, 0):
private void initGamePanel() {
gamePanel.setBackground(Color.BLUE);
gamePanel.setVisible(true);
gamePanel.setLayout(null);
player = new Player();
player.setLocation(100, 100);
player.setSize(100, 100);
player.setBackground(Color.CYAN);
gamePanel.add(player);
}
And another thing: when I set the x and y of player in the constructor, the position is equal to those values.
The class has the attributes x and y (which might be the problem
It could be, especially if you have getX()
and getY()
methods, since these are already implemented by a JPanel and should not be overridden.
Not sure if you really need the x/y attributes since you can just set the location of the component directly.
If you need these attributes for another reason then they should have a more descriptive name to avoid confusion with the class variables.
这篇关于setLocation 不适用于扩展 JPanel 的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!