我有一个名为" 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);
}
但是当我对" Player"做同样的事情时class,位置保持在(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);
}
另一件事:当我在构造函数中设置玩家的x和y时,位置等于这些值。
答案 0 :(得分:1)
该类具有属性x和y(可能是问题
可能是,特别是如果你有getX()
和getY()
方法,因为这些方法已经由JPanel实现,不应该被覆盖。
不确定您是否真的需要x / y属性,因为您可以直接设置组件的位置。
如果出于其他原因需要这些属性,那么它们应该具有更具描述性的名称,以避免与类变量混淆。