TITLE:Hyperlinkを、JLabel、JButton、JEditorPaneで表示

Posted by aterai at 2007-11-26

Hyperlinkを、JLabel、JButton、JEditorPaneで表示

Hyperlinkを、JLabel、JButton、JEditorPaneで表示し、それぞれクリックした時のイベントを取得します。

  • &jnlp;
  • &jar;
  • &zip;
HyperlinkLabel.png

サンプルコード

class URILabel extends JLabel {
  private final String href;
  public URILabel(String href) {
    super("<html><a href='"+href+"'>"+href+"</a>");
    this.href = href;
    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent e) {open(href);}
    });
  }
}
JButton button = new JButton(a);
button.setUI(LinkViewButtonUI.createUI(button));

class LinkViewButtonUI extends BasicButtonUI {
  private final static LinkViewButtonUI linkViewButtonUI = new LinkViewButtonUI();
  public static ButtonUI createUI(JButton b) {
    b.setBorder(BorderFactory.createEmptyBorder(0,0,2,0));
    b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    return linkViewButtonUI;
  }
  private LinkViewButtonUI() {
    super();
  }
  private static Dimension size = new Dimension();
  private static Rectangle viewRect = new Rectangle();
  private static Rectangle iconRect = new Rectangle();
  private static Rectangle textRect = new Rectangle();
  @Override
  public synchronized void paint(Graphics g, JComponent c) {
    AbstractButton b = (AbstractButton) c;
    ButtonModel model = b.getModel();
    Font f = c.getFont();
    g.setFont(f);
    FontMetrics fm = c.getFontMetrics(f);
    //...
JEditorPane editor = new JEditorPane("text/html", "<html><a href='"+MYSITE+"'>"+MYSITE+"</a>");
editor.setOpaque(false);
//editor.setBackground(getBackground());
//editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
editor.setEditable(false); //REQUIRED
editor.addHyperlinkListener(new HyperlinkListener() {
  public void hyperlinkUpdate(HyperlinkEvent e) {
    if(e.getEventType()==HyperlinkEvent.EventType.ACTIVATED) {
      java.awt.Toolkit.getDefaultToolkit().beep();
    }
  }
});

解説

上記のサンプルでは、クリックされた時に、リンクをブラウザで開く(Desktopでブラウザを起動)代わりに、beep音を鳴らしています。

  • JLabel+MouseListener
    • JLabelにMouseListenerを設定しています。
    • リンクの表示には<a>タグを使っています。
  • JButton+ButtonUI
    • JButtonに、文字の描画を変更するButtonUIを設定しています。
      • Rollover: アンダーライン
      • Pressed: 黒
  • JEditorPane+HyperlinkListener
    • 編集不可にしたJEditorPaneにHyperlinkListenerを設定しています。
    • リンクの表示には<a>タグを使っています。
    • 選択してコピーできます。

参考リンク

コメント