Reputation: 115
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.
Upvotes: 0
Views: 230
Reputation: 324147
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.
Upvotes: 1