我在JTextPane底部添加文本时遇到一些问题。在我做的所有研究中,我找到的唯一解决方案是将JTextPane添加到JPanel中。我的问题是我还有一个代码来包装文本行。文本换行和将JTextPane添加到JPanel中的组合不起作用。目前我的代码上有文本换行的东西,这里是:
package com.models;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import com.Config;
public class TextPane extends JTextPane
{
private static final long serialVersionUID = -8251523472372069488L;
private StyledDocument doc;
private Style style;
public TextPane()
{
DefaultCaret caret = (DefaultCaret) getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
setEditable(false);
setFont(new Font("Lucida Console", Font.PLAIN, 12));
setBackground(Color.LIGHT_GRAY);
setCaret(caret);
setEditorKit(new WrapEditorKit());
doc = getStyledDocument();
style = addStyle("Style", null);
}
public void append(Color color, String text)
{
StyleConstants.setForeground(style, color);
try
{
doc.insertString(doc.getLength(), Config.LINE_SEPARATOR + text, style);
}
catch (BadLocationException e)
{}
}
private class WrapEditorKit extends StyledEditorKit
{
private static final long serialVersionUID = -8173946569665645524L;
final ViewFactory defaultFactory = new WrapColumnFactory();
public ViewFactory getViewFactory()
{
return defaultFactory;
}
}
private class WrapColumnFactory implements ViewFactory
{
public View create(Element elem)
{
final String kind = elem.getName();
if (kind != null)
{
switch (kind)
{
case AbstractDocument.ContentElementName:
return new WrapLabelView(elem);
case AbstractDocument.ParagraphElementName:
return new ParagraphView(elem);
case AbstractDocument.SectionElementName:
return new BoxView(elem, View.Y_AXIS);
case StyleConstants.ComponentElementName:
return new ComponentView(elem);
case StyleConstants.IconElementName:
return new IconView(elem);
default:
return new LabelView(elem);
}
}
return new LabelView(elem);
}
}
private class WrapLabelView extends LabelView
{
public WrapLabelView(Element elem)
{
super(elem);
}
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);
}
}
}
}
我的问题是:如何进行文本换行并在JTextPane的底部插入文本