2011-09-30 8 views
3

나는 JEditorPane을 가지고 있습니다. 나는 간단한 편집자가 필요하다. 로드 및 사용자 지정 (두) 태그를 포함하는 HTML 수정 문제를 해결했습니다 (my older post 참조). 그것은 문서를 적절하게 표시하고 심지어 지금도 편집 할 수 있습니다. 나는 문자를 쓸 수 있으며, 문자 나 내 사용자 정의 요소를 삭제할 수 있습니다. 나는 전투에서 승리했지만 전쟁에서 승리하지 못했습니다. 다음 단계는 유감스럽게도 너무 problematical이다. 내 맞춤 태그를 삽입 할 수 없습니다. 그것은 제대로 worktsJEditorPane, HTMLEditorKit - 커스텀 태그를 삽입하는 커스텀 액션

import my.own.HTMLEditorKit; //extends standard HTMLEditorKit 
import my.own.HTMLDocument; //extends standard HTMLDocument 

class InsertElementAction extends StyledTextAction { 
    private static final long serialVersionUID = 1L; 

    public InsertElementAction(String actionName) { 
     super(actionName); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     JEditorPane editor = getEditor(e); 

     if (editor == null) 
      return; 

     HTMLDocument doc = (HTMLDocument) editor.getDocument(); 
     HTMLEditorKit ekit = (HTMLEditorKit) editor.getEditorKit(); 
     int offset = editor.getSelectionStart(); 

     try { 
      ekit.insertHTML(doc, offset, "<span>ahoj</span>", 0, 0, HTML.Tag.SPAN); 
      Element ele = doc.getRootElements()[0]; 
      ele = ele.getElement(1).getElement(0); 
      doc.setInnerHTML(ele, "<bar medium=\"#DEFAULT\" type=\"packaged\" source=\"identifier\" />"); 
     } 
     catch (BadLocationException ble) { 
      throw new Error(ble); 
     } 
     catch (IOException ioe) { 
      throw new Error(ioe); 
     } 
    } 
} 

:

나는 사용자 지정 작업이 있습니다. span 요소를 삽입 할 수 있습니다. 하지만 이런 방식으로 비표준 태그를 삽입 할 수는 없습니다. code, span 등을 삽입 할 수는 있지만 내 태그는 삽입 할 수 없습니다. 내 태그를 들어 나는이 사용하도록 강요 해요 : 두 가지 중요한 문제

  1. 사용자 정의 태그 (여기서 x)는 비 whispace 문자
  2. 으로 경계해야 있습니다

    ekit.insertHTML(doc, offset, "x<bar medium=\"#DEFAULT\" type=\"packaged\" source=\"identifier\" />x", 0, 0, null); 
    

    를 현재 요소의 예상대로 내가 <p>paragraph</p>span 요소를 삽입 할 때 몸이

을 분할, 나는 <p>par<span>ahoj</span>agraph</p>를 얻을. 알 수없는 태그 However가 항상 body 요소의 하위 요소로 삽입되고 결과 (예 : 알 수없는 태그 x)가 <p>par</p><x>ahoj</x><p>agraph</p>입니다.

작업이 완전히 소모되었습니다. 나는이 비교적 간단한 작업을 몇 주 동안 믿고 있습니다. 나는 벌써 낭비하고있다. 삽입이 작동하지 않을 경우, 나는 모두를 스크랩 할 수 있습니다 ...

+1

어떤 객체 유형이'AppErrors.EDITORKIT_ACTIONFAILURE'입니까? 'String'의 경우, Throwable (AppErrors.EDITORKIT_ACTIONFAILURE, ioe); –

+0

상관 없어요. 좀 더 종합적으로 업데이트 된 게시물을 보았습니다. –

+0

나는 이해하고 있는지 잘 모르겠다. HTMLEditorKit는 HTML 렌더링에 사용됩니다. HTML 태그가 아닌 태그로 피드하는 경우 어떻게해야할까요? –

답변

1

하는 데 도움이됩니다.

public void insertHTML(int offset, String htmlText) throws BadLocationException, IOException { 
    if (getParser() == null) 
     throw new IllegalStateException("No HTMLEditorKit.Parser"); 

    Element elem = getCurrentElement(offset); 

    //the method insertHTML is not visible 
    try { 
     Method insertHTML = javax.swing.text.html.HTMLDocument.class.getDeclaredMethod("insertHTML", 
       new Class[] {Element.class, int.class, String.class, boolean.class}); 
     insertHTML.setAccessible(true); 
     insertHTML.invoke(this, new Object[] {elem, offset, htmlText, false}); 
    } 
    catch (Exception e) { 
     throw new IOException("The method insertHTML() could not be invoked", e); 
    } 
} 

우리의 벽돌 상자의 마지막 조각이 방법은 찾고있다 : ModifiedHTMLDocument는 반사에 의해 숨겨진 medhod를 호출하는 방법 insertHTML()를 포함 내

ModifiedHTMLDocument doc = (ModifiedHTMLDocument) editor.getDocument(); 
int offset = editor.getSelectionStart(); 
//insert our special tag (if the tag is not bounded with non-whitespace character, nothing happens) 
doc.insertHTML(offset, "-<specialTag />-"); 
//remove leading and trailing minuses 
doc.remove(offset, 1); //at the current position is the minus before tag inserted 
doc.remove(offset + 1, 1); //the next sign is minus after new tag (the tag is nowhere) 
//Note: no, you really cannot do that: doc.remove(offset, 2), because then the tag is deleted 

: 태그는이 방법으로 삽입 현재 요소 :

public Element getCurrentElement(int offset) { 
    ElementIterator ei = new ElementIterator(this); 
    Element elem, currentElem = null; 
    int elemLength = Integer.MAX_VALUE; 

    while ((elem = ei.next()) != null) { //looking for closest element 
     int start = elem.getStartOffset(), end = elem.getEndOffset(), len = end - start; 
     if (elem.isLeaf() || elem.getName().equals("html")) 
      continue; 
     if (start <= offset && offset < end && len <= elemLength) { 
      currentElem = elem; 
      elemLength = len; 
     } 
    } 

    return currentElem; 
} 

이 방법은 또한 ModifiedHTMLDocument 클래스의 멤버이다.

이 솔루션은 순수하지는 않지만 일시적으로 문제를 해결합니다. 나는 더 나은 키트를 찾을 수 있기를 바랍니다. JWebEngine에 대해 생각하고 있습니다. 그건 현재의 가난한 사람 HTMLEditorKit을 대체해야하지만, 내 사용자 정의 태그를 추가 할 수 있는지 여부는 모르겠습니다.

2

희망이 내가 해결 방법을 발견했습니다 http://java-sl.com/custom_tag_html_kit.html

+0

나는 당신의 게시물의 도움으로 시작했습니다. 하지만 나는 아직 추가 할 것이 없다. 알 수없는 태그가 들어있는 파일을로드하는 방법입니다. 파일을로드 한 후 커스텀 태그를 삽입하는 데 약간의 만기가 있습니까? 하이퍼 텍스트를 편집하려면 내 사용자 정의 태그를 이미 편집기 창에로드 된 문서에 삽입 할 수 있어야합니다. 불행하게도 그것은 꽤 어렵습니다. –

+0

HTML을 삽입 할 때 동일한 메소드를 호출해야합니다. 따라서 태그가 인식되고 적절한 구조가 만들어집니다. – StanislavL

+0

어쨌든,'insertHTML()'메서드는 (개인적으로는 unsensually) private 메서드로 숨겨져 있습니다. 나는 insertBeforeStart() 만 사용할 수있다. 그럼에도 불구하고'setInnerHTML()'메소드는 무엇을 했는가? 태그가 흰색이 아닌 문자로 둘러싸여있을 때만 작동했다. 그렇지 않으면 어떤 조치도 취하지 않았습니다. 그것은 나에게 조금 웃기고 혼란스럽게 보입니다 ... –