cs106a – Assignment #2 – Task #3

Write a GraphicsProgram subclass that draws a partial diagram of the acm.program class hierarchy, as follows:

cs106a – assignment #2 – task #3

The only classes you need to create this picture are GRect, GLabel, and GLine. The major part of the problem is specifying the coordinates so that the different elements of the picture are aligned properly. The aspects of the alignment for which you are responsible are:

  • The width and height of the class boxes should be specified as named constants so that they are easy to change.
  • 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.
  • The connecting lines should start and end at the center of the appropriate edge of the box.
  • The entire figure should be centered in the window.

To draw a label (including its enclosing rectangular) centered at a given coordinate, first draw the rectangle where the top left corner is calculated by subtracting the halves of its size. The location of the label itself is has to be adjusted by half of its width and half of its ascent:

	private void drawLabel(String text, double x, double y) {
		GRect rect = new GRect(
			x - LABEL_WIDTH / 2, y - LABEL_HEIGHT / 2, 
		GLabel label = new GLabel(text);
			x - label.getWidth() / 2,
			y + label.getAscent() / 2

The lines between the rectangles are simple GLines:

	private void drawLine(double x1, double y1, double x2, double y2) {
		GLine line = new GLine(x1, y1, x2, y2);

The actual program consists of calculating the necessary positions and finally drawing the labels and the lines:

	public void run() {
		double cx = getWidth() / 2;
		double cy = getHeight() / 2;

		double xCenterOfLeftColumn = cx - LABEL_WIDTH - HORIZONTAL_GAP;		
		double xCenterOfRightColumn = cx + LABEL_WIDTH + HORIZONTAL_GAP;		
		double yMiddleOfFirstRow = cy - (LABEL_HEIGHT + VERTICAL_GAP) / 2;
		double yMiddleOfSecondRow = cy + (LABEL_HEIGHT + VERTICAL_GAP) / 2;

		double yBottomOfFirstRow = cy - VERTICAL_GAP / 2;
		double yTopOfSecondRow = cy + VERTICAL_GAP / 2;
		drawLabel("Program", cx, yMiddleOfFirstRow);
		drawLabel("GraphicsProgram", xCenterOfLeftColumn, yMiddleOfSecondRow);
		drawLabel("ConsoleProgram", cx, yMiddleOfSecondRow);
		drawLabel("DialogProgram", xCenterOfRightColumn, yMiddleOfSecondRow);

		drawLine(cx, yBottomOfFirstRow, cx, yTopOfSecondRow);
		drawLine(cx, yBottomOfFirstRow, xCenterOfLeftColumn, yTopOfSecondRow);
		drawLine(cx, yBottomOfFirstRow, xCenterOfRightColumn, yTopOfSecondRow);

The code for this assignment is available on github.


Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *