好的,我有以下问题,我用Java框架编写了一个简单的图形聊天客户端。为了显示接收到的消息,我使用一个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);...it不能工作(不显示文本),如果没有编辑器,它就能工作。有什么想法或暗示吗?
编辑
我认为问题是,我的定制EditorKit和StyledDocument不能同时工作.如果我通过键入msgPane.setText(text)插入文本,它就会工作!
发布于 2018-05-03 16:27:20
我自己解决了/阻止了这个问题。当我使用..。
JTextPane msgPane = new JTextPane();
msgPane.setEditorKit(new WrapEditorKit());
msgPane.getDocument().insertString(msgPane.getDocument().getLength(), text, null);...it工作,也与突出显示单个单词!这次我没有添加自定义DefaultStyledDocument,而是使用了msgPane.getDocument()返回的Document,现在它可以工作了。
如果有任何其他的解决方案,特别是使用自定义DefaultStyledDocument或对此问题的任何解释,我将很高兴……
https://stackoverflow.com/questions/50152438
复制相似问题