JTextPane 不会显示由 DefaultStyledDocument 添加的文本



好吧,我有以下问题,我用Java Swing框架编写一个简单的图形聊天客户端。为了显示收到的消息,我使用JTextPane.我遇到了一个问题,当一个用户从没有任何空格的单个字符发送消息时,JTextPane组件不会换行。我用下面的代码解决了这个问题,现在JTextPane组件不仅通过单词边界换行,如果长度不适合组件的宽度,也会换行任何字符。

public class WrapEditorKit extends StyledEditorKit
{
ViewFactory defaultFactory;
public WrapEditorKit()
{
this.defaultFactory = new WrapColumnFactory();
}
public ViewFactory getViewFactory()
{
return this.defaultFactory;
}
}
class WrapLabelView extends LabelView
{
public WrapLabelView(Element element)
{
super(element);
}
public float getMinimumSpan(int axis)
{
switch(axis)
{
case View.X_AXIS:
{
return 0;
}
case View.Y_AXIS:
{
return super.getMinimumSpan(axis);
}
default:
{
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
}
}
class WrapColumnFactory implements ViewFactory
{
public View create(Element element)
{
String kind = element.getName();
if(null != kind)
{
if(kind.equals(AbstractDocument.ContentElementName))
{
return new WrapLabelView(element);
}
else if(kind.equals(AbstractDocument.ParagraphElementName))
{
return new ParagraphView(element);
}
else if(kind.equals(AbstractDocument.SectionElementName))
{
return new BoxView(element, View.Y_AXIS);
}
else if(kind.equals(StyleConstants.ComponentElementName))
{
return new ComponentView(element);
}
else if(kind.equals(StyleConstants.IconElementName))
{
return new IconView(element);
}
}
return new LabelView(element);
}
}

我从网页上获得了很长时间的这段代码,我没有任何URL,它非常适合小型文本编辑面板。但是当我在上面这样的Document上添加文本时,它什么也不显示,它仅在我直接在窗格中键入单词时才有效,而当我在Document类的方法上添加文本时则无效......

StyleContext msgPaneStyle = new StyleContext();
final DefaultStyledDocument msgPaneDocument = new DefaultStyledDocument(this.msgPaneStyle);
JTextPane msgPane = new JTextPane(msgPaneDocument);
msgPane.setEditorKit(new WrapEditorKit());

如果我现在通过键入添加文本..

msgPaneDocument.insertString(msgPaneDocument.getLength(), text, null);

。它不起作用(不显示文本(,没有编辑器套件它可以工作。有什么想法或提示吗?

编辑

我认为问题是,我的自定义EditorKitStyledDocument不能同时工作......如果我通过键入msgPane.setText(text)插入文本,它可以工作!

我自己解决/阻止了这个问题。当我使用...

JTextPane msgPane = new JTextPane();
msgPane.setEditorKit(new WrapEditorKit());
msgPane.getDocument().insertString(msgPane.getDocument().getLength(), text, null);

。它有效,也可以突出显示单个单词!这次我没有添加自定义DefaultStyledDocument,而是使用了msgPane.getDocument()返回的Document,现在它可以工作了。

如果有任何其他解决方案,特别是使用自定义DefaultStyledDocument或对此问题的任何解释,我将很高兴......

最新更新