简体   繁体   中英

swing java app and iframe - two way communication

I have a java swing app and would like to render html pages in an iframe. Depending on what I do within the iframe, can parameters or data be passed back to my java swing app?

Thanks

You can take a look at JxBrowser library that allows embedding Google Chromium engine into Java Swing applications.

It provides API for two-way communication Java-to-JavaScript-to-Java: http://www.teamdev.com/downloads/jxbrowser/docs/JxBrowser-PGuide.html#javascript-java-bridge

The following code demonstrates how to embed Browser component, load URL, invoke JavaScript code on the loaded web page and register Java function on JavaScript side that will be invoked every time when JavaScript invokes it:

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;

/**
 * The sample demonstrates how to register a new JavaScript function and
 * map it to a Java method that will be invoked every time when the JavaScript
 * function is invoked.
 */
public class JavaScriptJavaSample {
    public static void main(String[] args) {
        Browser browser = BrowserFactory.create();
        // Register "MyFunction" JavaScript function and associate Java callback with it
        browser.registerFunction("MyFunction", new BrowserFunction() {
            public JSValue invoke(JSValue... args) {
                for (JSValue arg : args) {
                    System.out.println("arg = " + arg);
                }
                return JSValue.create("Hello!");
            }
        });

        // Create JFrame and embed Browser component to display web pages
        JFrame frame = new JFrame();
        frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // Register Load listener to get notification when web page is loaded completely
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    Browser browser = event.getBrowser();
                    // Invoke our registered JavaScript function
                    JSValue returnValue = browser.executeJavaScriptAndReturnValue(
                            "MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
                    System.out.println("return value = " + returnValue);
                }
            }
        });
        browser.loadURL("about:blank");
    }
}

Generally you would use a JEditorPane to display HTML.Swing supports HTML 3.2 (Wilbur) as Software Monkey said. You can find official documentation to this obsolescent (1996) version of HTML at: http://www.w3.org/TR/REC-html32.html

Java 7 documentation on the topic: http://docs.oracle.com/javase/7/docs/api/javax/swing/text/html/package-summary.html

Though it is worth of noting that it does not explicitly mention this information is valid for other Swing components.

Depending on your requirement there are two ways to go about this:

Swing components are actually added to the editor pane. So once the document has been parsed and the editor pane has been revalidated you should be able to just get a list of all the components added to the editor pane. You can check the class name to find the components you want.

The HTMLDocument contains attributes about each component added including the components model. So you can search the document to get the model for every checkbox.

Here is some general code to get your started:

import java.awt.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class GetComponent extends JFrame
{
    public GetComponent()
        throws Exception
    {
        FileReader reader = new FileReader("form.html");

        JEditorPane editor = new JEditorPane();
        editor.setContentType( "text/html" );
        editor.setEditable( false );
        editor.read(reader, null);

        JScrollPane scrollPane = new JScrollPane( editor );
        scrollPane.setPreferredSize( new Dimension(400, 300) );
        add( scrollPane );

        setDefaultCloseOperation( EXIT_ON_CLOSE );
        pack();
        setLocationRelativeTo( null );
        setVisible(true);

        //  display the attributes of the document

        HTMLDocument doc = (HTMLDocument)editor.getDocument();
        ElementIterator it = new ElementIterator(doc);
        Element element;

        while ( (element = it.next()) != null )
        {
            System.out.println();

            AttributeSet as = element.getAttributes();
            Enumeration enumm = as.getAttributeNames();

            while( enumm.hasMoreElements() )
            {
                Object name = enumm.nextElement();
                Object value = as.getAttribute( name );
                System.out.println( "\t" + name + " : " + value );

                if (value instanceof DefaultComboBoxModel)
                {
                    DefaultComboBoxModel model = (DefaultComboBoxModel)value;

                    for (int j = 0; j < model.getSize(); j++)
                    {
                        Object o = model.getElementAt(j);
                        Object selected = model.getSelectedItem();
                        System.out.print("\t\t");

                        if ( o.equals( selected ) )
                            System.out.println( o + " : selected" );
                        else
                            System.out.println( o );
                    }
                }
            }
        }

        //  display the components added to the editor pane

        for (Component c: editor.getComponents())
        {
            Container parent = (Container)c;
            System.out.println(parent.getComponent(0).getClass());
        }
    }

    public static void main(String[] args)
        throws Exception
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    GetComponent frame = new GetComponent();
                }
                catch(Exception e) { System.out.println(e); }
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM