centering a label inside a rectangle
hey,
I'm trying to complete q3 from this pdf.
http://www.stanford.edu/class/cs106a...signment-2.pdf
here is what ive written, so far it draws the middle line and the top box, but to me it looks like the label is off.
ive checked it and gone through it on paper and to me it should work fine (in theory), so now id like some help, see if someone else can spot my problem
here is my source. i have indicated the problem area in red.
Code :
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class ProgramHierarchy extends GraphicsProgram {
private static final int BOX_WIDTH = 120;
private static final int BOX_HEIGHT = 36;
private static final int MIDDLE_LINE_HEIGHT = 36;
private static final int GAP_BETWEEN_BOXES = 18;
public void run() {
placeMiddleLine();
placeTopBox();
}
private void placeMiddleLine() {
GLine middleLine = new GLine (getWidth()/2, (getHeight()/2) - (MIDDLE_LINE_HEIGHT)/2 , getWidth()/2, (getHeight()/2) + (MIDDLE_LINE_HEIGHT)/2);
add(middleLine);
}
private void placeTopBox() {
GRect topBox = new GRect ((getWidth()/2)-(BOX_WIDTH/2), ((getHeight()/2) - (BOX_HEIGHT)/2)-BOX_HEIGHT , BOX_WIDTH, BOX_HEIGHT);
add(topBox);
GLabel topLabel = new GLabel ("Program");
topLabel.setLocation((getWidth()/2) - (topLabel.getWidth()/2), (getHeight()/2) - (MIDDLE_LINE_HEIGHT/2) - (BOX_HEIGHT/2) + [COLOR="Red"](topLabel.getAscent()/2[/COLOR]));
add(topLabel);
}
}
also, in the pdf it says this
Quote:
The labels should be centered in their boxes. You can find the width of a label by calling label.getWidth() and the height it extends above the baseline by calling label.getAscent(). If you want to center a label, you need to shift its origin by half of these distances in each direction.
and to me that last part doesnt make sense. to me it should read something like
Quote:
If you want to center a label, you need to shift its origin by half of these distances in each direction relative to...
im not sure if these two issues are directly connected, but help on either one would be appreciated :)
Re: centering a label inside a rectangle
I tried replacing
with
Code :
(topLabel.getAscent()-topLabel.getDescent())/2
and now the label looks centered. is this the proper method?