I’m creating a Java swing GUI and I have formatted a JPanel to use a GridLayout. I need to access a specific “box” (i.e. specific coordinate) of the grid, but I cannot see a way to do so.
How can I do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You shouldn’t depend on GUI code (the View) to give you information about program data (the model). The best solution would be to “know” which component is where from the start–maybe you should have a data structure (2D array?) that holds the components and is updated whenever something’s added to the grid.
If you want a quick and very-dirty fix, though, you could start playing games with
JPanel.getComponentAt(). This requires pixel coordinates, though, so you’d need to do some reverse-engineering to figure out how much space a given grid square takes up. The space between grid squares is given by yourGridLayoutobject. This is not recommended whatsoever though. I’m just including it in the interest of completeness (and since it’s a more literal response to your question).