help with manipulating text in JPanel
hi all
i am writing an editor like MS Paint, my canvas is extending JPanel. I provide the facility to draw basic shape and text. I am getting trouble with text.
I have TextResource class which maintains input character in String and manipulate the key with StringBuffer when an character is typed and use TextLayout to display for user.
So I have to handle all input key stroke and i can handle BackSpace, Left and Right arrow key. But I cannot handle Space and Tab and the rest of whitespace.
So I am having the second thought that the java classes I used might not be appropriate. So please help me. Any suggestion will be appreciated! Thank you very much for your time.
here is some important code:
// in order to add a character into TextResource
// please ignore EBObjectAttribute, I used it for Property Table.
Code:
public void addCharacter(char c, int code) {
try {
StringBuffer buffer = new StringBuffer(text.getStringValue());
if (code == KeyEvent.VK_BACK_SPACE) {
if (this.cursorPosition > 0)
buffer.deleteCharAt(this.cursorPosition-1);
handleArrowKey(false);
this.text = new EBObjectAttribute(this, buffer.toString());
}
else if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_RIGHT) {
handleArrowKey(code == KeyEvent.VK_RIGHT);
}
else if (code == KeyEvent.VK_DELETE) {
if (this.cursorPosition >= 0 && this.cursorPosition < text.getStringValue().length())
buffer.deleteCharAt(this.cursorPosition);
this.text = new EBObjectAttribute(this, buffer.toString());
}
else {
if (Character.isDefined(c) && (code == KeyEvent.VK_SPACE || !Character.isWhitespace(c)))
buffer.insert(this.cursorPosition, c);
this.text = new EBObjectAttribute(this, buffer.toString());
handleArrowKey(true);
}
}
catch (Exception e) { }
}
// in order to handle cursor position: code from Java sun Tutorial
Code:
protected void handleArrowKey(boolean rightArrow) {
try {
if (text == null || text.getStringValue().length() == 0) {
this.cursorPosition = 0;
return;
}
textLayout = new TextLayout(this.text.getStringValue(), font, new FontRenderContext(null, false, false));
}
catch (Exception e) { }
TextHitInfo newPosition;
if (rightArrow)
newPosition = textLayout.getNextRightHit(this.cursorPosition);
else
newPosition = textLayout.getNextLeftHit(this.cursorPosition);
if (newPosition != null)
this.cursorPosition = newPosition.getInsertionIndex();
}