我有一个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);
}
}
只有一个问题:选择文本不再起作用,因为返回的getText字符串没有请求的长度(p1 – p0).实现JTextPane组件以精确选择多个字符,因此使用上述解决方案,用户只能选择p1-p0字符,即使新基本可能在模型中显示数字字符串的更长字符串表示.
那么,让View显示一个与模型中的String长度不同的String的正确方法是什么?我不想仅仅因为用户希望内容的不同表示而更新模型.
编辑:这是一个独立的例子.尝试选择文本 – 您只能选择所有字符或不选择字符,因为模型中只有一个字符.
package mini;
import javax.swing.*;
import javax.swing.text.*;
public class Mini extends JFrame {
public Mini() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTextPane pane = new JTextPane();
pane.setEditorKit(new MyEditorKit());
add(new JScrollPane(pane));
pack();
}
public static void main(String[] args) {
Mini mini = new Mini();
mini.setVisible(true);
}
}
class MyEditorKit extends StyledEditorKit {
@Override
public ViewFactory getViewFactory() {
return new ViewFactory() {
public View create(Element elem) {
return new MyView(elem);
}
};
}
}
class MyView extends LabelView {
public MyView(Element elem) {
super(elem);
}
@Override
public Segment getText(int p0, int p1) {
String line = "Displayed text that's longer than model text";
return new Segment(line.toCharArray(), 0, line.length());
}
}