2 Attachment(s)
Stanford CS106a GraphicsHeirarchy
Hi all
I've just started the Stanford CS106 online class as an intro to programming. In assignment 2 there's a problem where you have to write a program to display a class hierarchy as per this brief;
Attachment 3956
This is where I'm at in my solution;
public class GraphicsHierarchy extends GraphicsProgram {
private static final int BOX_WIDTH = 125;
private static final int BOX_HEIGHT = 50;
public void run() {
drawChart();
}
private void drawChart() {
drawTopBox();
drawBoxRow();
drawLines();
drawGObject();
}
private void drawTopBox() {
double x = getWidth() / 2 - BOX_WIDTH / 2;
double y = getHeight() / 2 - BOX_HEIGHT * 2;
GRect topBox = new GRect(x, y, BOX_WIDTH, BOX_HEIGHT);
add(topBox);
}
private void drawBoxRow() {
double x = getWidth() / 5 - (BOX_WIDTH / 2);
double y = getHeight() / 2 + BOX_HEIGHT;
for (int i = 4; i > 0; i--) {
GRect box = new GRect(x, y, BOX_WIDTH, BOX_HEIGHT);
add(box);
x += getWidth() / 5;
}
}
private void drawLines() {
double startlinex = getWidth() / 2;
double startliney = getHeight() / 2 - BOX_HEIGHT;
double endlinex = getWidth() / 5;
double endliney = getHeight() / 2 + BOX_HEIGHT;
for (int i = 4; i > 0; i--) {
GLine line = new GLine (startlinex, startliney, endlinex, endliney);
add(line);
endlinex += getWidth() / 5;
}
}
private void drawGObject() {
double x = getWidth() / 2 - BOX_WIDTH / 2;
double y = getHeight() / 2 - BOX_HEIGHT * 2;
GLabel text1 = new GLabel("GObject",x ,y );
text1.setFont("Helvetica-24");
add(text1);
I assumed I'd just stick the text into the boxes using label.getWidth() etc as per the brief. However, if I try and use it in the brackets after GLabel, it doesn't work because the GLabel isn't initiated till a couple of lines later.
So far the idea of top-down decomposition has been a big theme of the course, so I'm loath to go back to the drawing board and create the boxes around the labels. Or to press on with the lectures and book to use more sophisticated commands to solve the problem. Is there a way of moving the GLabel after its been initiated, or somehow manipulating it with label.getWidth?
Many thanks for your time and expertise!!!
Robbie