TITLE:JEditorPaneにリンクを追加
Posted by aterai at 2010-05-10

JEditorPaneにリンクを追加

JEditorPaneにリンクを追加します。
  • category: swing folder: HyperlinkListener title: JEditorPaneにリンクを追加 tags: [JEditorPane, Html, HTMLEditorKit, HyperlinkListener, JButton, Hyperlink] author: aterai pubdate: 2010-05-10T16:07:06+09:00 description: JEditorPaneに追加したリンクのクリックイベントなどをHyperlinkListenerで処理します。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTOK8UtUUI/AAAAAAAAAb8/yiME-hTTlWA/s800/HyperlinkListener.png

概要

JEditorPaneに追加したリンクのクリックイベントなどをHyperlinkListenerで処理します。
HyperlinkListener.png

サンプルコード

#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
final JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
#spandel
editorPane.setContentType("text/html"); //javax.swing.text.html.HTMLEditorKit
#spanend
#spandel
editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
#spanend
#spanadd
editorPane.setContentType("text/html");
#spanend
#spanadd
editorPane.putClientProperty(
#spanend
    JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
editorPane.setText(htmlText);
editorPane.addHyperlinkListener(new HyperlinkListener() {
  private String tooltip;
  @Override public void hyperlinkUpdate(HyperlinkEvent e) {
    if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      JOptionPane.showMessageDialog(editorPane, "You click the link with the URL " + e.getURL());
    }else if(e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      JOptionPane.showMessageDialog(
          editorPane, "You click the link with the URL " + e.getURL());
    } else if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
      tooltip = editorPane.getToolTipText();
      URL url = e.getURL();
      editorPane.setToolTipText((url!=null)?url.toExternalForm():null);
    }else if(e.getEventType() == HyperlinkEvent.EventType.EXITED) {
      editorPane.setToolTipText(Objects.nonNull(url) ? url.toExternalForm() : null);
    } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
      editorPane.setToolTipText(tooltip);
    }
  }
});

解説

上記のサンプルでは、JEditorPane(HTMLEditorKit,編集不可)に挿入したタグ"<a href='"+LINK+"'>"+LINK+"</a>"のクリックなどを受信するHyperlinkListenerを追加しています。

解説

上記のサンプルでは、JEditorPane(HTMLEditorKit,編集不可)に挿入したタグ<a href='...'>...</a>のクリックなどを受け取るHyperlinkListenerを追加しています。
  • - 以下のように、JButtonなどのコンポーネントを使用する方法もあります。
  • 編集可
  • 部分選択できない
  • ベースラインスがうまく揃わない?
  • 以下のように、JButtonなどのコンポーネントをアンカータグの代わりに使用する方法もある

参考リンク

コメント