Javaв„ў EE 5 Tutorial, The (3rd Edition)
Lesson | As you ll see in a moment, the TextModel code is quite a bit improved by this simple refining. It always seems to turn out this way. We repeatedly comb over the code, and little by little the snarls come out and it gets nicer and nicer. We re not done yet, but there s enough already to see that it s getting better. |
I ll include the whole TextModel code here now. My wife Ricia is home, so I ll leave it at that. Note especially that the lines.InsertRange and selectionStart = code looks very similar. We ll go after that in Chapter 12, Adding the Section Tag, Part II. For now, amuse yourself by reviewing the TextModel and observing that, by gosh, it is better:
using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; namespace Notepad { class TextModel { private ArrayList lines; private int selectionStart; public TextModel() { lines = new ArrayList(); } private int LineContainingCursor() { int length = 0; int lineNr = 0; int cr = Environment.NewLine.Length; foreach ( String s in lines) { if (length <= selectionStart && selectionStart < length+s.Length + cr ) break; length += s.Length + cr; lineNr++; } return lineNr; } public ArrayList Lines { get { return lines; } set { lines = value; } } public void SetLines(String[] lines) { this.Lines = new ArrayList(lines); } public String[] LinesArray() { String[] result = new String[lines.Count]; lines.CopyTo(result); return result; } public String TestText { get { StringBuilder b = new StringBuilder(); foreach(String s in lines) { b.Append(s); b.Append(System.Environment.NewLine); } b.Insert(SelectionStart,""); return b.ToString(); } } public int SelectionStart { get { return selectionStart; } set { selectionStart = value; } } public void Enter() { InsertParagraphTag(); } public void InsertParagraphTag() { if ( lines.Count == 0 ) { lines.Add( "<P></P>" ); selectionStart = 3; return; } lines.InsertRange(LineContainingCursor()+1, NewParagraph()); selectionStart = NewSelectionStart(LineContainingCursor() + 2, "<P>"); } public ArrayList NewParagraph() { ArrayList temp = new ArrayList(); temp.Add(""); temp.Add("<P></P>"); return temp; } public void AltS() { InsertSectionTags(); } public void InsertSectionTags() { if ( lines.Count == 0 ) { lines.Add( "<sect1><title></title>" ); lines.Add( "</sect1>"); selectionStart = 14; return; } lines.InsertRange(LineContainingCursor()+1, NewSection()); selectionStart = NewSelectionStart(LineContainingCursor() + 1, "<sect1><title>"); } public ArrayList NewSection() { ArrayList temp = new ArrayList(); temp.Add("<sect1><title></title>"); temp.Add("</sect1>"); return temp; } private int NewSelectionStart(int cursorLine, string tags) { return SumLineLengths(cursorLine) + tags.Length; } private int SumLineLengths(int cursorLine) { int length = 0; for (int i = 0; i < cursorLine; i++) length += ((String)lines[i]).Length + Environment.NewLine.Length; return length; } } }
Категории