91 lines
2.6 KiB
Java
91 lines
2.6 KiB
Java
package stateandbehavior;
|
|
|
|
public class LineEditor {
|
|
|
|
private String text = "";
|
|
private int insertionIndex = 0;
|
|
|
|
|
|
/** flytter tekstinnsettingsposisjonen ett tegn til venstre (tilsvarende bruk av venstre piltast) */
|
|
public void left() {
|
|
this.insertionIndex -= (this.insertionIndex != 0) ? 1 : 0;
|
|
}
|
|
|
|
/** flytter tekstinnsettingsposisjonen ett tegn til høyre (tilsvarende bruk av høyre piltast) */
|
|
public void right() {
|
|
this.insertionIndex += (this.insertionIndex != this.text.length()) ? 1 : 0;
|
|
}
|
|
|
|
/** skyter teksten angitt av argumentet s inn i teksten på tekstinnsettingsposisjonen og forskyver tekstinnsettingsposisjonen mot høyre tilsvarende */
|
|
public void insertString(String s) {
|
|
this.text = this.text.substring(0, this.insertionIndex)
|
|
+ s
|
|
+ this.text.substring(this.insertionIndex);
|
|
this.insertionIndex += s.length();
|
|
}
|
|
|
|
/** fjerner tegnet til venstre for tekstinnsettingsposisjonen */
|
|
public void deleteLeft() {
|
|
if (this.insertionIndex != 0) {
|
|
this.text = this.text.substring(0, this.insertionIndex - 1)
|
|
+ this.text.substring(this.insertionIndex);
|
|
this.insertionIndex--;
|
|
}
|
|
}
|
|
|
|
/** fjerner tegnet til høyre for tekstinnsettingsposisjonen */
|
|
public void deleteRight() {
|
|
if (this.insertionIndex != this.text.length())
|
|
this.text = this.text.substring(0, this.insertionIndex)
|
|
+ this.text.substring(this.insertionIndex + 1);
|
|
}
|
|
|
|
/** returnerer teksten */
|
|
public String getText() {
|
|
return this.text;
|
|
}
|
|
|
|
|
|
/** oppdaterer teksten til å være den nye teksten */
|
|
public void setText(String s) {
|
|
this.text = s;
|
|
|
|
}
|
|
|
|
/** returnerer hvor i teksten redigeringer nå skjer */
|
|
public int getInsertionIndex() {
|
|
return this.insertionIndex;
|
|
}
|
|
|
|
/** oppdaterer hvor i teksten redigeringer skal skje */
|
|
public void setInsertionIndex(int i) {
|
|
this.insertionIndex = i;
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return this.text.substring(0, this.insertionIndex)
|
|
+ "|"
|
|
+ this.text.substring(this.insertionIndex);
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
LineEditor lineeditor = new LineEditor();
|
|
lineeditor.setText("test");
|
|
System.out.println(lineeditor);
|
|
lineeditor.right();
|
|
System.out.println(lineeditor);
|
|
lineeditor.left();
|
|
System.out.println(lineeditor);
|
|
lineeditor.setInsertionIndex(2);
|
|
System.out.println(lineeditor);
|
|
lineeditor.deleteRight();
|
|
System.out.println(lineeditor);
|
|
lineeditor.deleteLeft();
|
|
System.out.println(lineeditor);
|
|
lineeditor.insertString("ex");
|
|
System.out.println(lineeditor);
|
|
}
|
|
|
|
}
|