【问题标题】:how to get access to widget inside JEditorPane?如何访问 JEditorPane 中的小部件?
【发布时间】:2012-06-13 04:13:51
【问题描述】:

我正在使用 JEditorPane 来显示 html 文本。如果html文件包含

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

JEditorPane 将在编辑器小部件中放置一个文本字段小部件。我想做的是检索文本字段中的值。如何检索文本字段的文本值或小部件?

【问题讨论】:

    标签: java html swing jeditorpane


    【解决方案1】:

    HTML 控件被添加到封装在私有内部类 Invalidator extends Container 中的 JEditorPane 中。

    因此您可以获得 JEditorPane 的所有子组件。它们中的每一个都应该是 Invalidator 实例。 Invalidator 的唯一子元素是编辑组件本身(例如,JTextFlied 用于 &lt;input&gt; 标记)。

    【讨论】:

    • 您好 Stanislav,在您发布您的建议之前,我曾尝试过类似的想法。我没有走很远。我到了失效器组件,就像你说的那样。但这就是我卡住的地方。我无法比这个组件更进一步。 getComponentAt 不是子级。接下来,我假设失效器组件是最后一个,并尝试向它添加几个侦听器。那些听众没有被触发。我的下一个选择是拦截并创建 componentView 而不是使用默认值。
    【解决方案2】:

    当您在 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
        // ...      
    }
    

    【讨论】:

      【解决方案3】:

      感谢斯坦尼斯拉夫花时间回答。尝试检索组件对我来说太难了。我找到了解决问题的方法。我希望这对其他人有帮助。虽然我找不到访问小部件的方法,但我可以创建自己的文本小部件并替换默认小部件。这样我就可以控制小部件。为此,您必须继承 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_);
          }
      }
      

      对于要控制的每种类型的小部件,您必须至少执行一次此操作。这是一种痛苦,但它确实有效。

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 1970-01-01
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多