【问题标题】:Is it possible to set length of paragraph in JTextPane StyledDocument?是否可以在 JTextPane StyledDocument 中设置段落长度?
【发布时间】:2014-08-08 07:37:55
【问题描述】:

我正在使用JTextPaneStyledDocument,是否可以设置其段落的长度? 我的目标是当 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


【解决方案1】:

试试这个:

public static void main(String[] args) throws Exception {
    final JTextPane pane = new JTextPane();
    pane.setContentType("text/html");
    final JFrame frm = new JFrame("Text editor");
    pane.setText("<html><table><tr><td width=\"400\"></td></tr></table</html>");
    frm.add(new JScrollPane(pane));
    frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frm.setSize(500, 500);
    frm.setVisible(true);
}

您的文字将在 400 像素后换行

【讨论】:

  • 如果我将 StyledDocument 设置为 HTML,我将无法使用我为每种文本类型定义的样式。
  • @user90 您可以使用 HTML 表示法定义您的样式。
  • &lt;td width=\"400\"&gt;.. 400 什么?字符、像素、..?
  • @Sergiy Medvynskyy 我还向我的 JTextPane 添加了一些组件,它们的对齐方式应设置为向右或向左取决于它们的类型。如何通过将内容类型设置为 html 来设置它们的对齐方式?
  • 不。根据 W3C,宽度是 pxem%(或无效)。我们不应该相信 Swing 工具包中的“默认值”。例如。 JFrame 以前默认为 FlowLayout。这真的塞满了很多应用程序。当 Sun 决定更改默认布局为 BorderLayout
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 2018-07-22
  • 1970-01-01
  • 2021-09-11
相关资源
最近更新 更多