0

So I'm basically in a predicament. I'm trying to find the location of a JButton using the .getLocation() accessor, however this only seems to work for me if I put it after the window is set as visible - otherwise it only returns x as 0 and y as 0. I cannot put this after the window is set visible in my particular case as if I do this, the buttons aren't initialised in the first place. I'm basically wondering if their is an accessor that finds the location of these buttons before the window is set as visible? Here's the code I'm using that returns x & y as 0:

    public class Test {
    public Test() {
        JButton buttonOne = new JButton();
        JButton buttonTwo = new JButton();
        JPanel panel = new JPanel();
        JFrame window = new JFrame("Test");
        GridLayout g = new GridLayout();

        panel.add(buttonOne);
        panel.add(buttonTwo);
        panel.setLayout(g);
        System.out.println(buttonTwo.getLocation());


        window.setContentPane(panel);
        window.setSize(512, 512);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}
George Z.
  • 6,643
  • 4
  • 27
  • 47
James Corin
  • 35
  • 1
  • 5
  • 1
    Possible duplicate of [*How to get X and Y index of element inside GridLayout?*](https://stackoverflow.com/q/7702697/230513) – trashgod Mar 14 '19 at 11:39
  • 1
    Why do you care about the location? The layout manager will set the size and location of the components once you pack() the frame or make the frame visible. – camickr Mar 14 '19 at 14:21
  • On a wider scale I'm trying to make a checkers game, so I need to be able to find the location of the button so that I can move it around the board (i.e. the checkers piece). – James Corin Mar 15 '19 at 12:32

1 Answers1

0

It's most likely not the visibility that's the problem but rather that there hasn't been a layout yet. Swing layouts don't recalculate everything every time a control is added or removed.

Making the window visible is just one way of enforcing that the contents have been laid out. Another one would be explicitly calling pack().

Joey
  • 344,408
  • 85
  • 689
  • 683
  • Hi, thanks for the reply. I did actually try putting the layout first but that didn't work either (still returned 0,0), it only seems to work if I put the window as visible before getting the location. I think because it reads the location off the screen? Not entirely sure. – James Corin Mar 14 '19 at 09:00
  • @James, did you explicitly call `pack()` before trying to find the location of the button? – Joey Mar 14 '19 at 09:47