Question

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?

Was it helpful?

Solution

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 your GridLayout object. 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).

OTHER TIPS

In GridLayout, "The container is divided into equal-sized rectangles." You can add an empty, transparent component in places you want to appear empty, e.g. new JLabel(""). See also GridBagLayout and Using Layout Managers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top