TITLE:JToolTipにアイコンを表示
#navi(../)
RIGHT:Posted by [[terai]] at 2006-02-13
*JToolTipにアイコンを表示 [#i911af83]
JToolTipにアイコンを表示します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#fe5cdb35]
#code{{
JLabel l1 = new JLabel("JLabelを使ってツールチップにアイコン") {
  public JToolTip createToolTip() {
    JToolTip tip = super.createToolTip();
    tip.setLayout(new BorderLayout());
    JLabel iconlabel = new JLabel("テスト", icon, SwingConstants.LEFT);
    iconlabel.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
    tip.add(iconlabel);
    Insets i = tip.getInsets();
    Dimension d = iconlabel.getPreferredSize();
    int w = d.width+i.left+i.right;
    int h = d.height+i.top+i.bottom;
    tip.setPreferredSize(new Dimension(w,h));
    return tip;
  }
}; l1.setToolTipText("");
}}
#code{{
JLabel l2 = new JLabel("MatteBorderでツールチップにアイコン") {
  public JToolTip createToolTip() {
    JToolTip tip = super.createToolTip();
    Dimension d = tip.getPreferredSize();
    int strw = SwingUtilities.computeStringWidth(
                  tip.getFontMetrics(tip.getFont()), "テスト");
    Border b1 = tip.getBorder();
    Border b2 = BorderFactory.createMatteBorder(
                  0, icon.getIconWidth(), 0, 0, icon);
    Border b3 = BorderFactory.createEmptyBorder(1,1,1,1);
    Border b4 = BorderFactory.createCompoundBorder(b3, b2);
    tip.setBorder(BorderFactory.createCompoundBorder(b1, b4));
    Insets i = tip.getInsets();
    int w = strw+i.left+i.right+3; // 3?
    int h = Math.max(d.height, icon.getIconHeight()+i.top+i.bottom);
    tip.setPreferredSize(new Dimension(w,h));
    return tip;
  }
}; l2.setToolTipText("テスト");
}}
#code{{
JLabel l3 = new JLabel("htmlタグでツールチップにアイコン");
l3.setToolTipText("<html><img src='"+url+"'>テスト</img></html>");
}}

**解説 [#j592553f]
-上ラベル
--JToolTipにJLabelを追加しています。
-中ラベル
--MatteBorderを使ってアイコンを表示するように、createToolTipメソッドをオーバーライドしています。
-下ラベル
--htmlのimgタグをsetToolTipTextメソッドに使ってアイコンを表示しています。

**参考リンク [#rbfe7317]
-[[XP Style Icons - Windows Application Icon, Software XP Icons>http://www.icongalore.com/]]
--アイコンを利用しています。

**コメント [#w823ef7d]
- MatteBorderを使うと1.4と1.5で表示が微妙に異なるようです。 -- [[terai]] &new{2006-02-13 (月) 14:57:57};
- JLabelをJToolTipに貼る方法を追加しました。 -- [[terai]] &new{2006-07-05 (水) 18:40:54};
- 「MatteBorderでツールチップにアイコン」で、MatteBorderとEmptyBorderの内外が反対になっていたのを修正しました。 -- [[terai]] &new{2006-07-05 (水) 19:15:11};

#comment