package rebelsky.text; /** * A simple representation of a line or part of a line of text. * TextLines are much like Strings, but we make them a different * class for convenience (e.g., in case we want to add capabilities). * * @author Samuel A. Rebelsky * @author Everyone else in CSC152 2005S */ public class TextLine implements TextBlock { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The contents of the line. */ String contents; /** A collection of spaces used for padding. */ String spaces; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** Build a new TextLine from a string. */ public TextLine(String _contents) { this.contents = _contents; this.spaces = " "; } // TextLine(String) // +-------------------+--------------------------------------- // | TextBlock Methods | // +-------------------+ /** Get the width of this line. */ public int getWidth() { return this.contents.length(); } // getWidth() /** Get the number of lines in this block. */ public int getLines() { return 1; } // getLines() /** Get a line of this block. */ public TextLine getLine(int n) throws Exception { if (n == 0) return this; else throw new Exception("This block has only 1 line."); } // getLine(int) // +---------------+------------------------------------------- // | Other Methods | // +---------------+ /** Get the text on this line. */ public String toString() { return this.contents; } // toString() /** Change the text on this line. */ public void setContents(String newcontents) { this.contents = newcontents; } // setContents(String) /** Get this line represented as a specific width. */ public String atWidth(int width) { // Remember the length of this line, since we use it // many times in the code to follow. int len = this.contents.length(); if (len >= width) return this.contents.substring(0,width); else { while (len + this.spaces.length() < width) this.spaces = this.spaces + this.spaces; return this.contents + this.spaces.substring(0, width-len); } } // atWidth(int) } // class TextLine