gpt4 book ai didi

java - setLocation 不适用于扩展 JPanel 的类

转载 作者:行者123 更新时间:2023-12-01 09:06:41 24 4
gpt4 key购买 nike

我有一个名为“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”类执行相同操作时,位置保持在 (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 时,位置等于这些值。

最佳答案

The class has the attributes x and y (which might be the problem

可能是这样,特别是如果您有 getX()getY() 方法,因为这些方法已经由 JPanel 实现,不应该被覆盖。

不确定您是否真的需要 x/y 属性,因为您可以直接设置组件的位置。

如果您出于其他原因需要这些属性,那么它们应该有一个更具描述性的名称,以避免与类变量混淆。

关于java - setLocation 不适用于扩展 JPanel 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41213167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com