Question

I've inserted a few JPanels in a GridBagLayout, with the gridBagConstraints object, and after a specific action I want to change the color of some JPanels. My question is how do I access the specific JPanels in the GridBagLayout and change their colors. (with given coordinates of the Jpanels in the grid)

Was it helpful?

Solution

You should assign those JPanels to some sort of variable in order to be able to get a reference to them. This could be individual variables, or a collection such as a List or Map. If you haven't yet used Maps, then I would recommend that you give careful towards using these very helpful constructs which can allow you to gain access to an object based on a String, their "coordinates" or some other unique identifier.

As an aside, my suggestion obviously has nothing to do with the layout manager, and I don't think that trying to use the layout manager for this will lead to a robust long-term solution.

If you must get the GridBagConstraints for an individual component in the GridBagLayout-using container, per the GridBagLayout API you could use the GridBagLayout method, public GridBagConstraints getConstraints(Component comp). If you needed this for all components, then you could call getComponents() on your container, iterate through all the Components in a for loop, calling the above method on them.

Also, if you need more specific help, then consider editing your question by creating and posting a minimal code example program for us to review, test, and possibly help you fix.

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