[英]Java - How to fix size of html tags to their contents in JTextPane?
我有一個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 ...屬性尚未呈現。 ( CSS類 )
由於對CSS屬性的支持有限,因此我插入的所有<p>
元素都具有相同的長度,但是我想設置寬度的最大尺寸,因此,如果text
尺寸較長,則換行,如果較短,則背景固定為其內容。
屏幕截圖是img.rar中的Untitled1。
編輯1:
我使用BorderLayout
將Pane
添加到JPanel
。
panel = new JPanel(new BorderLayout());
編輯2:
我將插入文本的html代碼更改為以下內容:
doc.insertBeforeEnd(content, "<table class = 'text'><tr><td>"+text+"</td></tr></table>");
現在它修復了內容(img.rar中為Untitled2),但是我想設置最大寬度,並將表格放在html的中心。
屏幕截圖的圖片
問題有兩個部分。
第一個如何定義width屬性以及如何從模型Element中獲取它。 嘗試研究HTMLDocument樹元素並嘗試獲取400。
第二部分相對容易一些。 如果您可以從Element中讀取寬度設置(從屬性或樣式中讀取),則可以覆蓋HTMLEditorKit的ViewFactory中的javax.swing.text.html.ParagraphView並為getPreferredSpan /返回400(寬度prom屬性/樣式/樣式) getMinumumSpan / getMaximumSpan和X_AXIS
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.