【问题标题】:Java call back in swing htmlSwing html中的Java回调
【发布时间】:2016-06-28 14:46:48
【问题描述】:

我们在 Swing 应用程序中使用 HTML 来绘制表格

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?

我知道有 3rd 方库,例如 JxBrowser,像 example,但是,我们首先查看是否有办法通过使用内置组件来做到这一点,而无需将 3rd 方库添加到分布式应用程序中。

【问题讨论】:

  • 这听起来像是JTable 的工作..
  • @Andrew Thompson 是的,谢谢,大多数应用程序确实使用 JTables,但是在一个特定的地方,出于内部特定原因,选择了 html。

标签: javascript java html swing callback


【解决方案1】:

我希望能够在其中一个表格单元格内单击,以调用 java 类回调,也许是通过 javascript?或任何其他选择? 例如,单击将调用 java 方法执行某些工作的表格单元格,并打开一些对话框窗口。

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

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

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

【讨论】:

  • 不知道 HyperlinkListener,谢谢!有没有办法从链接传递信息?即单元格有一些唯一的 id,我希望事件得到它。 href 中的“a1”会在“getDescription()”中吗?
  • 欢迎您。 Will the "a1" from the href will be in the "getDescription()" 是的...这将是一种传递信息的方式,以便您知道事件来自哪个“链接”
  • 感谢 copeg 的帮助,我会试试的
猜你喜欢
  • 2013-02-02
  • 2012-12-19
  • 2023-03-20
  • 2011-07-04
  • 2014-01-18
  • 1970-01-01
  • 2015-12-26
  • 2011-02-27
  • 1970-01-01
相关资源
最近更新 更多