• category: swing folder: IconTitledBorder title: TitledBorderのタイトルにアイコンを表示する tags: [Border, TitledBorder, ImageIcon, Html] author: aterai pubdate: 2015-09-07T00:03:04+09:00 description: TitledBorderのタイトルに文字列だけでなく、アイコンを表示するように設定します。 image: https://lh3.googleusercontent.com/-CoxU1H7Z550/VexP9UAQdbI/AAAAAAAAOBI/QIVGOXu5MNE/s800-Ic42/IconTitledBorder.png

概要

TitledBorderのタイトルに文字列だけでなく、アイコンを表示するように設定します。

サンプルコード

URL url = getClass().getResource("16x16.png");
String path = url.toString();
String title = String.format(
  "<html><table cellpadding='0'><tr><td><img src='%s'></td><td>test</td></tr></table></html>", path);
panel.setBorder(BorderFactory.createTitledBorder(title));
View in GitHub: Java, Kotlin

解説

  • <img>
    • TitledBorder#setTitle(...)<img>タグでアイコンを指定したHtmlテキストを設定
    • Class#getResource(...)でアイコンのURLを取得し、<img>のソースに指定
    • アイコンとテキストのベースラインが揃っていない
  • <table> + <img>
    • <table><tr>タグを使用して、アイコンとテキストのベースラインを揃える
  • TitledBorder#paintBorder(...)
    • TitledBorder#paintBorder(...)をオーバーライドしてアイコンを描画
    • タイトル文字列に半角空白で余白を作成し、位置を決め打ちでアイコンを描画
  • ComponentTitledBorder

参考リンク

コメント