Load javascript within JFrame or JPanel

寵の児 提交于 2019-12-24 10:25:44

问题


I would like to load a the below javascript code to a JPanel or a JFrame. Is it possible?

<script language="javascript" type="text/javascript" charset="utf-8">
//javascript code
</script>

回答1:


You can use third-party libraries: such as HtmlUnit

It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use.

Example:

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class JavaScriptProgram
{
    private WebClient webClient;
    private HtmlPage currentPage;

    public JavaScriptProgram()
    {
        webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
        webClient.setThrowExceptionOnScriptError(false);
        webClient.setJavaScriptEnabled(true);
    }

    public void visitPage(String url)
    {
        try
        {
            currentPage = (HtmlPage) webClient.getPage(url);
        }
        catch(Exception e)
        {
            // Cannot get the page
        }
    }

    public void executeJavaScript(String code)
    {
        currentPage.executeJavaScript(code);
    }

    public static void main(String[] args)
    {
        JavaScriptProgram p = new JavaScriptProgram();
        p.visitPage("http://www.stackoverflow.com");
        p.executeJavaScript("document.write('Hello World!');");
    }
}



回答2:


If you want browser capability within your Swing app, you could check Lobo, it supports Javascript too.




回答3:


Swing components doesn't support Javascript codes natively. If you really need integrate Javascript and Java, you can try Rhino. But remember: it's javascript language only, you cannot use browser's API.



来源:https://stackoverflow.com/questions/9548459/load-javascript-within-jframe-or-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!