我有一个StyledDocument实例,其中包含代表数字的字符串.通过覆盖字符串元素的属性,我正在使用我从LabelView派生的自定义视图.我想允许用户选择显示数字的基数,例如十进制或十六进制.这是我目前的解决方案:
public class AddressView extends LabelView {
@Override
public Segment getText(int p0, int p1) {
// get string representation of the number from the model
String stringNumber = super.getText(p0, p1).toString();
// get base from document's attributes
int base = getDocument().getProperty(BaseProperty);
// convert string to desired base
String stringNumberOverride = Integer.toString(Integer.parseInt(stringNumber), base);
// return as segment (can have a different length, JTextPane doesn't like that)
char[] strNum = stringNumberOverride.toCharArray();
return new Segment(strNum, 0, strNum.length);
}
}
Run Code Online (Sandbox Code Playgroud)
只有一个问题:选择文本不再起作用,因为返回的getText字符串没有请求的长度(p1 - p0).实现JTextPane组件以精确选择多个字符,因此使用上述解决方案,用户只能选择p1-p0字符,即使新基本可能在模型中显示数字字符串的更长字符串表示.
那么,让View显示一个与模型中的String长度不同的String的正确方法是什么?我不想仅仅因为用户希望内容的不同表示而更新模型.
编辑:这是一个独立的例子.尝试选择文本 …