urir urir - 5 months ago 20
HTML Question

Java call back in swing html

We are using HTML to draw a table in our swing application

String html = generateHtml();
this.textPane = new JTextPane();
HTMLEditorKit kit = new HTMLEditorKit();
textPane.setEditorKit(kit);
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("th, td {width: 50px; text-align: center;}");
Document doc = kit.createDefaultDocument();
textPane.setDocument(doc);
textPane.setContentType("text/html");
textPane.setText(html);
textPane.setEditable(false);
textPane.setBackground(null);
textPane.setBorder(null);
textPane.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
this.add(textPane);


I would like to be able to click inside one of the table cells, to invoke a java class callback, maybe through javascript? or any other option?

For example, to click a table cell that will call a java method to do some work, and open some dialog window.

Maybe this can done through javascript to callback the java? or directly from html to java?


I know there are 3rd party libraries, such as JxBrowser, like this example, however, we are first looking if there is a way to do that by using built in components, without 3rd party library added to the distributed app.

Answer

I would like to be able to click inside one of the table cells, to invoke a java class callback, maybe through javascript? or any other option? For example, to click a table cell that will call a java method to do some work, and open some dialog window.

Presuming you are displaying relatively simplistic content, you could wrap the contents of the table cells in links, and use a hyperlink listener to process the click events on the links. A simple example:

JTextPane editor = new JTextPane();
editor.setContentType("text/html");
editor.setText("<html><body><table><tr><td><a href=\"a1\" >Cell1</a></td><td><a href=\"a2\">Cell2</a></td></tr></table></body></html>");
editor.addHyperlinkListener(new HyperlinkListener(){

    @Override
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if ( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED ){
            System.out.println(e.getDescription());
        }

    }

});
editor.setEditable(false);

You will need to set additional styles for links if you don't wish to have the default styles (color, underline, etc...).