【问题标题】:How to make my webbrowser able to use JavaScript in Java?如何让我的网络浏览器能够在 Java 中使用 JavaScript?
【发布时间】:2012-01-29 18:15:42
【问题描述】:

在我的 Java Web 浏览器中,javascript alert() 无法正常工作,如何使其处于活动状态?

例子:

package www;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

public class HtmlEditorKitTest {
  public static void main(String[] args) {
    new HtmlEditorKitTest();
  }

  public HtmlEditorKitTest() {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JEditorPane jEditorPane = new JEditorPane();
        jEditorPane.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(jEditorPane);
        HTMLEditorKit kit = new HTMLEditorKit();
        jEditorPane.setEditorKit(kit);
        StyleSheet styleSheet = kit.getStyleSheet();
        styleSheet.addRule("body {color:#000; font-family:times; margin: 4px; }");
        styleSheet.addRule("h1 {color: blue;}");
        styleSheet.addRule("h2 {color: #ff0000;}");
        styleSheet.addRule("pre {font : 10px monaco; color : black; background-color : #fafafa; }");
        String htmlString = "<html>\n"
                          + "<body>\n"
                          + "<script>alert('Show Javascript works or not');</script>\n"
                          + "<h1>Welcome!</h1>\n"
                          + "<h2>H2 header</h2>\n"
                          + "<p>Text description</p>\n"
                          + "<p><a href=\"http://www.google.com/can/whynot?Oracle?/\">SiteOpen</a></p>\n"
                          + "</body>\n";

        Document doc = kit.createDefaultDocument();
        jEditorPane.setDocument(doc);
        jEditorPane.setText(htmlString);
        JFrame j = new JFrame("WebBrowser in Java");
        j.getContentPane().add(scrollPane, BorderLayout.CENTER);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.setSize(new Dimension(300,200));
        j.setLocationRelativeTo(null);
        j.setVisible(true);
      }
    });
  }
}

【问题讨论】:

标签: java javascript swing mozilla chromium


【解决方案1】:

称某物为网络浏览器并不能使其成为网络浏览器。

来自HTMLEditorKit API:

Swing JEditorPane 文本组件通过称为 EditorKit 的插件机制支持不同类型的内容。因为 HTML 是一种非常流行的内容格式,所以默认提供了一些支持。此类提供默认支持,它支持 HTML 3.2 版(带有一些扩展),并且正在向 4.0 版迁移。不支持&lt;applet&gt; 标签,但为&lt;object&gt; 标签提供了一些支持。

【讨论】:

  • 在制作了一个功能性的小程序上下文和环境后,我在JEditorPane的编辑器工具包中添加了对applet元素的支持(用于Appleteer)。我做到了,但这是整个过程中最艰难的部分。
猜你喜欢
  • 2014-02-26
  • 2010-10-10
  • 1970-01-01
  • 2011-11-27
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多