有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing html中的javascript Java回调

我们正在使用HTML在swing应用程序中绘制表格

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);

我希望能够在其中一个表单元格中单击,调用java类回调,可能是通过javascript?还是其他选择
例如,单击一个将调用java方法的表单元格来做一些工作,并打开一些对话框窗口
也许这可以通过javascript来回调java?还是直接从html到java

我知道有第三方库,比如JxBrowser,像这样的example,但是,我们首先看看是否有一种方法可以通过使用内置组件来做到这一点,而不向分布式应用程序添加第三方库


共 (1) 个答案

  1. # 1 楼答案

    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.

    假设显示的内容相对简单,可以将表格单元格的内容包装在链接中,并使用超链接侦听器处理链接上的单击事件。一个简单的例子:

    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);
    

    如果不希望使用默认样式(颜色、下划线等),则需要为链接设置其他样式