我有一个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;}");
我知道浮动,清除,...属性尚未渲染。 (Class CSS)
由于CSS属性的支持有限,我插入的所有<p>
元素都具有相同的长度,但我想为宽度设置最大大小,因此如果text
大小更长,则包装,如果它更短,则背景固定为其内容。
img.rar中的Untitled1是截图。
EDIT1:
我使用Pane
将JPanel
添加到BorderLayout
。
panel = new JPanel(new BorderLayout());
EDIT2:
我更改了我的html代码,以便将文字插入以下内容:
doc.insertBeforeEnd(content, "<table class = 'text'><tr><td>"+text+"</td></tr></table>");
现在它修复了内容(img.rar中的Untitled2)但我想设置最大宽度,并将表放在html的中心。
截图&#39>图片
答案 0 :(得分:0)
问题有2部分。
第一个如何定义width属性以及如何从模型Element获取它。尝试调查HTMLDocument树元素并尝试获取400。
第二部分相对容易一些。如果您可以从Element中读取宽度设置(来自属性或样式),您可以覆盖HTMLEditorKit的ViewFactory中的javax.swing.text.html.ParagraphView并返回getPreferredSpan /的400(宽度prom属性/ style / attribte) getMinumumSpan / getMaximumSpan和X_AXIS