package gve.calc.formula;
import java.awt.*;
public class StringPartView extends CursorPosLabel implements KeydnListener,View,MouseSensitive {
private StringPart model;
public StringPartView(StringPart model) {
super("");
setForeground(Color.blue);
this.model = model;
MVC.registerView(model,this);
updateView(null);
}
Model has changed; reflect changes visually. |
public void updateView(Object arg) {
setText("\""+model.getString()+"\"");
}
public Object getModel() { return model; }
public boolean mousePressed(int flags,int x,int y) { return false; }
// almost same as StaticStringView.mouseDown
public void mouseDown(int flags,int x,int y) {
FontMetrics fm = getFontMetrics(getFont());
String string = getText();
int len = string.length();
FormulaView view = FormulaView.get(this);
for (int i = 0; i < len; i++) {
int w = fm.charWidth(string.charAt(i));
if (x < w/2) {
view.setCursorComp(this,i);
return;
}
x -= w; // advance one letter to the right
}
// Place cursor at the rightmost position
view.setCursorComp(this,len);
}
public boolean keydn(int key) {
int cp = getCursorPos();
switch(key) {
case Key_LEFT:
if (cp > 0) {
setCursorPos(cp - 1);
repaint();
return true;
}
break;
case Key_RIGHT:
if (cp < getText().length()) {
setCursorPos(cp + 1);
repaint();
return true;
}
break;
case Key_BS:
if (cp==0 || cp==getText().length()) {
// oopsie
} else {
if (cp == 1) return true;
String txt = model.getString();
txt = txt.substring(0,cp-2) + txt.substring(cp-1);
model.setString(txt);
setCursorPos(cp-1);
}
invalidate();
return true;
case Key_DEL:
if (cp==0 || cp==getText().length()) {
// oops
} else {
String txt = model.getString();
if (cp-1 == txt.length()) return true;
txt = txt.substring(0,cp-1) + txt.substring(cp);
model.setString(txt);
}
invalidate();
return true;
default:
if (key < 32) return false;
{ String txt = model.getString();
txt = new String(new StringBuffer(txt).insert(cp-1,(char)key));
setCursorPos(cp + 1);
invalidate(); // mark me for resizing
model.setString(txt);
}
return true;
}
return false;
}
}