【问题标题】:Java - How to fix size of html tags to their contents in JTextPane?Java - 如何在 JTextPane 中将 html 标签的大小固定为其内容?
【发布时间】:2014-08-14 21:37:05
【问题描述】:

我有一个JTextPane,带有 html 内容:

    Pane = new JTextPane();
    Pane.setEditable(false);
    Pane.setContentType("text/html");
    Pane.setEditorKit(kit);
    Pane.setText("<html><body><div id='content'></div></body></html>");
    doc = (HTMLDocument) Pane.getStyledDocument();
    content = doc.getElement("content");

我在运行时添加了我的 html 元素:

doc.insertBeforeEnd(content, "<p class = 'text'>"+text+"</p>"); // text is input from user

这是我使用的 CSS:

    styleSheet = doc.getStyleSheet();
    styleSheet.addRule("body{background-color:#FFFFFF;}");
    styleSheet.addRule("#content {margin: 0% 10%; width : 80%; }");
    styleSheet.addRule("img {height : 10px; width : 10px;  }");
    styleSheet.addRule(".text{display: inline-block;background-color:#E2EAF3;margin : 2px;padding : 1px 10px;; border-radius: 4px;border-width: 1px;border-style: solid;border-color: #D5D3CD;text-align: right;clear: both;float: right;}");

我知道 float,clear,... 属性尚未渲染。 (Class CSS)

由于对 CSS 属性的支持有限,我插入的所有 &lt;p&gt; 元素都具有相同的长度,但我想为宽度设置最大尺寸,所以如果 text 尺寸较长,它会换行,如果它比固定到其内容的背景短。

img.rar中的Untitled1是截图。

编辑1:

我用BorderLayoutPane 添加到JPanel

panel = new JPanel(new BorderLayout());

EDIT2:

我将用于插入文本的 html 代码更改为以下内容:

doc.insertBeforeEnd(content, "<table class = 'text'><tr><td>"+text+"</td></tr></table>");

现在它修复了内容(img.rar 中的 Untitled2),但我想设置最大宽度,并将表格放在 html 的中心。

截图的图片

【问题讨论】:

    标签: java html css swing jtextpane


    【解决方案1】:

    问题有两部分。

    第一个如何定义宽度属性以及如何从模型元素中获取它。尝试调查 HTMLDocument 树元素并尝试获取 400。

    第二部分相对容易一些。如果您可以从元素中读取宽度设置(从属性或样式),您可以覆盖 HTMLEditorKit 的 ViewFactory 中的 javax.swing.text.html.ParagraphView 并为 getPreferredSpan/ 返回 400(宽度 prom 属性/样式/属性) getMinumumSpan/getMaximumSpan 和 X_AXIS

    【讨论】:

    • 我更改了我的 html 代码(我编辑了我的帖子),所以现在我的问题是设置最大宽度...,你能帮我解决这个问题吗!
    猜你喜欢
    • 2011-11-08
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多