int rightMostX = firstBound.x;
int numOfPanels = selectedPanels.size();
for (int i = 0; i < numOfPanels; i++) {
Panel panel = selectedPanels.get(i);
Rectangle bound = panel.getBounds();
int oldx = bound.x;
int width = bound.width;
if (oldx < leftMostX)
leftMostX = oldx;
if (oldx + width > rightMostX)
rightMostX = oldx + width;
}
for (Panel panel : selectedPanels) {
Rectangle bound = panel.getBounds();
//
// Algorithm: the bounding box is determined by finding the
// rightmost edge
// along with the left most edge. The difference between
// these two points is the area lengthwise of the bounding box.
//
// distance = rightMostX - leftMostX;
//
// Thus, the center of the bounding area would be the would
// be the x position that is midway between the bounding length
// added to the leftmost edge:
//
// midwayPoint = leftMostX + (distance / 2);
//
// So, to center align each box in the bounding box, find that
// component's midway point (x pos + (width / 2)).
// move that component such that it's midway
// point is equal to the bounding box midway point. Thus,
// all items are aligned.
int midwayPoint = leftMostX + ((rightMostX - leftMostX) / 2);
int componentMidwayPoint = bound.x + (bound.width / 2);
if (componentMidwayPoint > midwayPoint) { // it's to the right of
// the center - move it
// back
int diff = componentMidwayPoint - midwayPoint;
panel.setBounds(bound.x - diff, bound.y, bound.width, bound.height);
} else { // it's to the left of center - move it towards the
// center...
int diff = midwayPoint - componentMidwayPoint;
panel.setBounds(bound.x + diff, bound.y, bound.width, bound.height);
}
}
}