我有带有html内容的JTextPane,我添加了带有我的CSS规则的StyleSheet。 我想在我的html元素中插入JComponent,以便CSS规则在其上执行。 html会是这样的:
<body>
<div id = 'content'>
<p class = 't'>t</p>
<p class = 'k'>k</p>
<div class = 'hascomp'>
<span class = 'desc'>description</span>
<br/>
// here I want to insert my java component
</div>
</div>
</body>
以下是使用hascomp类创建元素的java代码:
try {
doc.insertBeforeEnd(content, "<div class = 'hascomp'><span class = 'desc'>"+description+"</span><br/>");
} catch (BadLocationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int offset = Pane.getDocument().getLength();
Pane.setCaretPosition(offset);
Pane.insertComponent(jcomponent);
try {
doc.insertBeforeEnd(content, "</div>");
} catch (BadLocationException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
hascomp类的CSS:
.hascomp {font : 10px monaco; background-color:#E15AE3;margin : 2px;padding : 1px 10px;border-radius: 4px;border-width: 1px;border-style: solid;border-color: #D5D3CD;text-align: left;clear: both;float: left; }
但它无法正常工作。
here is picture of running code
那么,如何在JTextPane的html元素中嵌入JComponent?!
答案 0 :(得分:0)
我在这个问题上努力工作。我找到的唯一解决方案是使用HTMLEditorKit
中的insertHTML插入标记你可以这样做:
protected void insertComponent(Component c, long id) {
if (this.getSelectedText() != null && this.getSelectedText().length()>0) {
try {
htmlDoc.remove(this.getSelectionStart(), this.getSelectedText().length());
} catch (BadLocationException ex) {
Logger.getLogger(Editeur.class.getName()).log(Level.SEVERE, null, ex);
}
}
int position = getSelectionStart();
MutableAttributeSet inputAttributes = new SimpleAttributeSet();
StyleConstants.setComponent(inputAttributes, c); //add component
inputAttributes.addAttribute(COMPONENT_ID_ATTRIBUTE, id);//add id attribute
insertComponent(position, id, c, inputAttributes);
}
private boolean insertComponent(int position, String id, Component c, AttributeSet inputAttributes) {
try {
String toInsert = "<span id='"+id+"'> </span>";
int pushDepth, popDepth;
pushDepth = isEOL(position-1) ? 1 : 0;//HACK:you have to check for end-of-lines before current position
popDepth = pushDepth;
editorKit.insertHTML(htmlDoc, position, toInsert, popDepth, pushDepth, Tag.SPAN);
htmlDoc.setCharacterAttributes(position, 1, inputAttributes, false);
//HACK you need to add/remove a dummy element to refresh the document structure. I didn't succeed with normal commands...
htmlDoc.insertString(position+1, " ", null);
htmlDoc.remove(position+1, 1);
return true;
} catch (IOException | BadLocationException ex) {
Logger.getLogger(Editeur.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}