In a Java project I’m working on, I am using a GridBagLayout to lay out my UI. Every component in the UI has associated with it an x and y coordinate, which the GridBagConstraints uses to place the component in the UI.
I have a method addAt(component, x, y, constraints) that will place a given component at the coordinates (x,y) in the UI.
Rather than doing the following to set up my UI:
addAt(component1, 3, 1, constraints);
addAt(component2, 3, 2, constraints);
addAt(component3, 3, 3, constraints);
addAt(component4, 3, 4, constraints);
I would like to store the coordinates of each component in the object itself, which would give me:
addAt(component1, constraints);
addAt(component2, constraints);
addAt(component3, constraints);
addAt(component4, constraints);
My current approach to doing this is to override the base classes for all JComponents I’m using, and implement an interface with methods getXCoord() and getYCoord().
I have seen that JComponents have the methods getX() and getY(), but the purpose of those methods is different than what I’m going for.
So basically, my question is, given the above information, is there a cleaner way to implement this functionality than creating overridden versions of every individual JComponent? I apologize if I am missing something obvious here.
You could use a mediator or the
get/putClientPropertymethods to store the associations between components and coordinates and query it to retrieve the coordinates on theaddAtmethod.Your coordinates can be like this:
And you use it in your
addAt:You create the association, for example, like this: