# Axel Werner's OPEN SOURCE Knowledge Base

### Site Tools

it-artikel:java:a-solution-on-assignment-2-problem-3

# A Solution on Assignment 2 - Problem 3

This is “a” Solution of Assignment 2 - Problem 3 from the Computer Science Course CS106A of Prof. Mehran Sahami at the STANFORD University.

In fact, i cant realy tell anymore if I wrote this code or if i found it somewhere on the internet :). It looks pretty much like programm code i usualy make. But will not claim that this is MY Code. Just a Code that solves the Problem as requested for example purposes.

ProgramHierarchy.java
```/*
* File: ProgramHierarchy.java
* Name:
* ---------------------------
* This file is the starter file for the ProgramHierarchy problem.
*/

import acm.graphics.*;
import acm.program.*;

public class ProgramHierarchy_example_solution1 extends GraphicsProgram {

public static final double BOX_WIDTH = 200.0;
public static final double BOX_HEIGHT = 80.0;

public void run() {
double horizontalMargin = (getWidth() - BOX_WIDTH * 3) / 4;
double verticalMargin = (getHeight() - BOX_HEIGHT * 2) / 3;

double x = horizontalMargin * 2 + BOX_WIDTH;
double y = verticalMargin;

GRect box1 = drawBox(x, y, "Program");

x = horizontalMargin;
y = verticalMargin * 2 + BOX_HEIGHT;

GRect box2 = drawBox(x, y, "GraphicsProgram");

x = horizontalMargin * 2 + BOX_WIDTH;
y = verticalMargin * 2 + BOX_HEIGHT;

GRect box3 = drawBox(x, y, "ConsoleProgram");

x = horizontalMargin * 3 + BOX_WIDTH * 2;
y = verticalMargin * 2 + BOX_HEIGHT;

GRect box4 = drawBox(x, y, "DialogProgram");

drawConnectingLine(box1, box2);
drawConnectingLine(box1, box3);
drawConnectingLine(box1, box4);
}

public GRect drawBox (double x, double y, String text) {

GRect box = new GRect (x, y, BOX_WIDTH, BOX_HEIGHT);

GLabel label = new GLabel (text, x, y);

x = x  + BOX_WIDTH / 2 - label.getWidth() / 2;
y = y + BOX_HEIGHT / 2 + label.getAscent() / 2 ;

label.setLocation (x, y);

return box;
}

public void drawConnectingLine(GRect fromBox, GRect toBox) {

double fromX = fromBox.getX() + BOX_WIDTH / 2;
double fromY = fromBox.getY() + BOX_HEIGHT;

double toX = toBox.getX() + BOX_WIDTH / 2;
double toY = toBox.getY();

GLine line = new GLine (fromX, fromY, toX, toY); 