2012-04-12 56 views
0

我正在使用JEditorPane來顯示html文本。如果HTML文件包含如何獲取JEditorPane中的小部件?

<form action="WORK3.html" method="get"> 
    <input type="text" value="Enter your name here!" size="25"> 
</form> 

JEditorPane中會放一個文本框控件編輯器部件內。我想要做的是檢索文本字段中的值。如何檢索文本字段的文本值或小部件?

回答

1

將HTML控件添加到包裝在私有內部類中的JEditorPane Invalidator擴展Container。

因此,您可以獲取JEditorPane的所有子組件。它們中的每一個都應該是Invalidator實例。 Invalidator的唯一孩子是編輯組件本身(例如,標記爲<input>的JTextFlied)。

+0

嗨斯坦尼斯拉夫,你發佈你的建議之前,我用類似的想法有點發揮各地。我沒有走得很遠。我遇到了失效者組件,你喜歡你說的。但這是我陷入困境的地方。我無法獲得比這個組件更遠的地方。 getComponentAt不產生子對象。接下來,我假設invalidator組件是最後一個,並嘗試添加一對聽衆。那些聽衆沒有被觸發。我的下一個選擇是截取並創建componentView,而不是使用默認值。 – tadpole 2012-04-13 13:45:43

0

感謝斯坦尼斯拉夫抽空回答。嘗試檢索組件對我來說太難了。我找到了解決問題的辦法。我希望這會幫助別人。雖然我無法找到訪問該小部件的方法,但我可以創建自己的文本小部件並替換默認的小部件。這樣我就可以控制小部件。爲此,您必須繼承HTMLEditorKit.HTMLFactory的子類。在這個類中,你需要重寫

public View create (Element elem_) { 
    Document doc = elem_.getDocument(); 
    Object obj = elem_.getAttributes(). 
     getAttribute(StyleConstants.NameAttribute); 

    HTML.Tag tag = (HTML.Tag) obj; 

    if (tag.toString().equals ("input")) { 
     // you can replace your widget here if you want 
     // i choose to use the default but save the view for 
     // my own use later 
     ComponentView view = (ComponentView)super.create (elem_); 
     // save the component view to where you want to access 
     // later. you can retrieve the component from the 
     // ComponentView and cast it to back to JTextField 
     _editor.saveView (view); 

     return (view); 
    } 

    else { 
     return (super.create (elem_); 
    } 
} 

你必須爲你想控制每個類型的widget這樣做至少一次。這是一種痛苦,但卻能完成這項工作。

0

當你在一個textPane中插入一個組件時,你只需要從它的Invalidator類中「解開」它。

//Loop through the components, maybe looking for some in particular 

for (Component cont : myTextPane.getComponents()) { 
//Unwrap your component, means take the only one component from the wrapper container 
    Component comp = ((Container) cont).getComponent(0); 

    //Do your things with your component 
    // ...  
}