0

我有带有 html 内容的 JTextPane,我添加了带有我的 CSS 规则的 set 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; }

但它不能正常工作。

这是运行代码的图片

那么,如何将 JComponent 嵌入到 JTextPane 的 html 元素中?!

4

1 回答 1

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+"'>&nbsp;</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;
}
于 2014-09-16T06:50:45.640 回答