Q:

Cleanly adding a little functionality to a lot of classes

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.

A:

You could use a mediator or the get/putClientProperty methods to store the associations between components and coordinates and query it to retrieve the coordinates on the addAt method.
Your coordinates can be like this:
class Coordinates {
  private final int x;
  private final int y;
  public Coordinates(int x, int y) {
    this.x = x;
    this.y = y;
  }
  public int getX() { return x; }
  public int getY() { return y; }
}

And you use it in your addAt:
private void addAt(JComponent component, GridBagConstraints constraints) {
  Coordinates coordinates = (Coordinates)component.getClientProperty("coords");
  int x = coordinates.getX();
  int y = coordinates.getY();

  // place it in the grid...
}

You create the association, for example, like this:
public void setUpComponentsCoordinates() {
  component1.putClientProperty("coords", new Coordinates(3, 1));
  component2.putClientProperty("coords", new Coordinates(3, 2));
  component3.putClientProperty("coords", new Coordinates(3, 3));
  component4.putClientProperty("coords", new Coordinates(3, 4));
}

