• category: swing folder: TitledBorderHorizontalInsetOfText title: TitledBorderにタイトル文字列までの内余白を設定する tags: [TitledBorder, Border, JLabel] author: aterai pubdate: 2017-04-03T15:46:05+09:00 description: 左寄せのTitledBorderで、ボーダーの左端からタイトル文字列までの内余白を設定するテストを行います。 image: https://drive.google.com/uc?id=17kiVkxVACOFeT1HK8R68epgwBPGtzRYMJQ

概要

左寄せのTitledBorderで、ボーダーの左端からタイトル文字列までの内余白を設定するテストを行います。

サンプルコード

// Space between the border and the component's edge
protected static final int EDGE_SPACING = 2; // 2px;

// Space between the border and text
protected static final int TEXT_SPACING = 5; // 2px;

// Horizontal inset of text that is left or right justified
protected static final int TEXT_INSET_H = 10; // 5px;
View in GitHub: Java, Kotlin

解説

  • override TitledBorder#paintBorder(...)
    • TitledBorder#paintBorder(...)をオーバーライドして、ボーダーの描画位置を10px右に移動
    • タイトル文字列までの内余白は変化せず、また中身のコンポーネントは移動しないのでボーダーと重なる
  • override TitledBorder#getBorderInsets(...)
    • TitledBorder#getBorderInsets(...)をオーバーライドして、ボーダーの左内余白を10px増加
    • タイトル文字列までの内余白は変化しないが、中身のコンポーネントが10px右に移動する
  • ComponentTitledBorder + EmptyBorder
    • 文字列ではなくJLabelをタイトルとして描画するComponentTitledBorderを使用し、JLabelの描画開始位置を10px右に移動
    • タイトル文字列までの10pxの内余白にボーダーが描画され、タイトルに使用するJLabelに設定したEmptyBorder分の5pxは空白になり合計15pxの内余白が生成される
  • TitledBorder2: copied from TitledBorder
    • 内余白の設定が外部から変更できないので、TitledBorderを全てコピーしてTEXT_SPACINGTEXT_INSET_Hの値だけ変更
    • TEXT_INSET_H2pxから10pxに変更したため、ボーダーからタイトル文字列までの間に10pxの内余白が生成される
    • TEXT_SPACING2pxから5pxに変更したため、上記の内余白から5px分ボーダーが描画されない空白が生成される
      • ボーダーと中身のコンポーネントとの余白も、この値を変更すると増減してしまう?

参考リンク

コメント