GLabeledBox Part 2


In the first part, I went over a basic skeleton of a class to create a labeled box object using the ACM library in Java.  The first just drew both the label and the box at the same point.  I need to center the label, and I do so here.

This version is almost useful- while it needs the ability to set the size and location of the box, it does display the box and put the label in the right position.

The core thing I changed is rather than setting the label object directly in the constructor, I broke that out into a separate method, as it’s becoming somewhat more complicated.  Technically it could al be done in one line in the constructor, but that code would be painful to read.  Sometimes you run across a problem that actually requires painful code, but that’s rare, and certainly not this time.

public void setLabel(String l){
	label = new GLabel(l);
		
	/* X location is middle of the box, shifted left by half the text
	 * pixel width, centering it horizontally*/
	double labelX = (box.getX() + .5 * BOX_WIDTH) - .5 * label.getWidth();
	/* Y location is middle of the box, shifted down by half the text
	 * pixel height, centering it vertically */
	double labelY = (box.getY() + .5 * BOX_HEIGHT) + .5 * label.getAscent();
	label.setLocation(labelX, labelY);
}

It is important to note the coordinate system- (0,0) is in the upper right for the ACM graphics library.  Moving to the left means a negative change in X, moving down means a positive change in Y.  GRects are places based on their upper left corner, GLabels are placed based on their lower left(exclusive of any hanging bits like in a ‘g’).  It’s simpler to imagine where the complete box will go if its coordinates are based on those of the GRect, and then place the label relative to it.  In principle I could have switched this, but that would have made it a little harder to reason about what code using this class is doing and where things will show up on the screen.  If this was more of a bordered text thing, though, it might make sense to build everything off the label.  That’s not what I’m doing here though.

I then simply changed the line in the constructor that set the label to:

setLabel("Hello");

I’ll be changing the code to allow setting of box size and location shortly, but that’s trivial enough I may not post it.
 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: