package rebelsky.text; /** * A simple representation of the horizontal composition of two * blocks of text. * * @author Samuel A. Rebelsky * @author Everyone else in CSC152 2005S */ public class HorizontallyCompose implements TextBlock { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** * The stuff on the left */ TextBlock left; /** * The stuff on the right. */ TextBlock right; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Surround a simple text block. * * @pre * The block is not null * @exception Exception * If the block is null. */ public HorizontallyCompose(TextBlock _left, TextBlock _right) throws Exception { if ((_left == null) || (_right == null)) throw new Exception("Cannot compose null text"); this.left = _left; this.right = _right; } // HorizontallyCompose(TextBlock) // +----------------+------------------------------------------ // | Public Methods | // +----------------+ /** * Determine the width of the composed block. */ public int getWidth() { return this.left.getWidth() + this.right.getWidth(); } // getWidth() /** * Determine the number of lines of the composed block. */ public int getLines() { if (this.left.getLines() > this.right.getLines()) return this.left.getLines(); else return this.right.getLines(); } // getLines() /** * Determine the nth line of this block. Lines are numbered * starting with 0. * * @exception Exception * If an invalid line number is given. */ public TextLine getLine(int n) throws Exception { // Compute the number of lines in the left and right, because we // use those values repeatedly. int leftlines = this.left.getLines(); int rightlines = this.right.getLines(); // Compute the width of the left b/c we use it repeatedl. int leftwidth = this.left.getWidth(); // Normal case: Within both blocks if ((n < leftlines) && (n < rightlines)) return new TextLine(this.left.getLine(n).atWidth(leftwidth) + this.right.getLine(n).toString()); // Special case: No right else if ((n < leftlines) && (n >= rightlines)) return this.left.getLine(n); // Special case: No left else if ((n >= leftlines) && (n < rightlines)) { // STUB return this.right.getLine(n); } // Default: Crash and burn. else throw new Exception("Invalid line number."); } // getLine() } // class HorizontallyCompose