• title: JEditorPaneにリンクを追加 tags: [JEditorPane, Html, HTMLEditorKit, HyperlinkListener, JButton] author: aterai pubdate: 2010-05-10T16:07:06+09:00 description: JEditorPaneにリンクを追加します。

概要

JEditorPaneにリンクを追加します。

サンプルコード

final JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.setContentType("text/html");
editorPane.putClientProperty(
    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) {
      tooltip = editorPane.getToolTipText();
      URL url = e.getURL();
      editorPane.setToolTipText((url != null) ? url.toExternalForm() : null);
    } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
      editorPane.setToolTipText(tooltip);
    }
  }
});
View in GitHub: Java, Kotlin

解説

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


以下のように、JButtonなどのコンポーネントを使用する方法もあります。

HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
Style s = doc.addStyle("button", null);
StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
HyperlinkButton button = new HyperlinkButton(new AbstractAction(LINK) {
  @Override public void actionPerformed(ActionEvent e) {
    AbstractButton b = (AbstractButton) e.getSource();
    editorPane.setBackground(b.isSelected() ? Color.RED : Color.WHITE);
    JOptionPane.showMessageDialog(
        editorPane, "You click the link with the URL " + LINK);
  }
});
button.setToolTipText("button: " + LINK);
button.setOpaque(false);
StyleConstants.setComponent(s, button);
try {
  doc.insertString(doc.getLength(), "\n----\nJButton:\n", null);
  doc.insertString(doc.getLength(), LINK + "\n", doc.getStyle("button"));
  //doc.insertString(doc.getLength(), "\n", null);
} catch (BadLocationException ble) {
  ble.printStackTrace();
}

参考リンク

コメント