【发布时间】:2014-08-08 07:37:55
【问题描述】:
我正在使用JTextPane 和StyledDocument,是否可以设置其段落的长度?
我的目标是当 JTextPane 中插入的文本长度超过 400 像素时,超过转到新行。
编辑:
我使用下面的方法来设置 textPane 的样式
public Style getstyle(String message){
Style style = context.addStyle("mystyle", null);
StyleConstants.setForeground(style, Color.GRAY);
StyleConstants.setBackground(style, new Color(162, 234, 167));
SimpleAttributeSet mystyle = new SimpleAttributeSet();
StyleConstants.setFontFamily(style, "SansSerif");
document.setParagraphAttributes(document.getLength(), message.length(), mystyle, false);
return style;
}
并使用以下内容将文本插入到我的 JTextPane:
try {
document.insertString(document.getLength(), " "+message+"\n", getStyle(message));
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我想设置段落的长度。
编辑2:
我为不同类型的文本使用不同的样式。
编辑3:
我使用滚动条将JTextPane 添加到JPanel。
context = new StyleContext();
document = new DefaultStyledDocument(context);
Pane = new JTextPane(document);
Pane.setEditable(false);
Panel.setLayout(new BoxLayout(Panel, BoxLayout.PAGE_AXIS));
JScrollPane scroll = new JScrollPane(Pane);
Panel.add(scroll , BorderLayout.CENTER);
【问题讨论】:
-
如果
StyledDocument恰好是HTML,文档的宽度可以由所使用的CSS来建议。请参阅this answer,了解如何使用JLabel格式的HTML。 -
是文本,如何设置ot为text/html?
-
发布您的代码。与您在之前的问题中被问到的相同。为您提供了几种不同的方法。向我们展示您的最佳尝试。
-
@StanislavL 我编辑我的问题并发布我的代码
-
BorderLayout 不关心大小。它只是放大滚动以填充所有可用宽度。尝试使用另一个 LayoutManager
标签: java swing jtextpane styleddocument