my problem is, that when I create a JButton, whithin its constructor, I set its location to some relative coordinates, say x = 5, and y = 6, using the following code:
this.setLocation(new Point(x, y));
but after I am trying to get its location using the getLocation() method, it always returns 0,0. Please note that this happens for every JButton I am trying to place on a grid layout powered JFrame, and during the debugging process, I have also noted that their location is being properly instantiated.
Can someone explain to me why this happens, and if I can fix it somehow?
EDIT:
The constructor (The brick class that I made, extends JButton):
public Brick(int posx, int posy) {
this.setLocation(new Point(posx, posy));
this.setVisible(true);
}
I make about 100+ of them in 2 for loops:
for (int row = 0; row < 15; row++) {
for (int column = 0; column < 15; column++) {
Brick brickie = new Brick(row, column);
}
}
But afterwards, if I wanna pick a brick and check its location like this:
Point brickLocation = brickie.getLocation();
both brickLocation.x == 0 and brickLocation.y == 0
You are trying to change button location when it is automatically assigned by layout manager (your GridLayout). That is why you are always getting the same value back – layout just overwrites it.
To be able to change any component bounds/location (including buttons) manually – you have to set “null” as the container’s layout. After that just change the location/size/bounds as you like and it will affect the components positions.
Also you don’t need to use “setVisible(true)” – by default that flag is true for all components (even those that aren’t displayed yet).