• category: swing folder: InsertComponentBaseline title: JTextPaneに追加するコンポーネントのベースラインを揃える tags: [JTextPane, JComponent, Baseline] author: aterai pubdate: 2012-09-03T06:06:39+09:00 description: JTextPaneに追加するコンポーネントのベースラインが他の文字列などとを揃うように設定します。 image: https://lh3.googleusercontent.com/-JveOiooEbAg/UEPEjv1VW2I/AAAAAAAABR4/qts-97h_JuA/s800/InsertComponentBaseline.png

概要

JTextPaneに追加するコンポーネントのベースラインが他の文字列などとを揃うように設定します。

サンプルコード

JCheckBox check1 = new JCheckBox("JComponent.setAlignmentY(...)");
Dimension d = check1.getPreferredSize();
int baseline = check1.getBaseline(d.width, d.height);
check1.setAlignmentY(baseline / (float) d.height);
textPane.replaceSelection("\n\n Baseline: ");
textPane.insertComponent(check1);
View in GitHub: Java, Kotlin

解説

  • 上: Default
    • JTextPane#insertComponent(...)で、JCheckBoxを追加
    • JCheckBoxのデフォルトのAlignmentY0.5なのでテキストのベースラインと揃わない
  • 中: JComponent#setAlignmentY(...)
    • JComponent#getBaseline()でベースラインを取得し、JComponent#setAlignmentY(baseline/(float)d.height)でテキストベースラインの相対位置に配置
  • 下: setAlignmentY+setCursor+...
    • 「中: JComponent#setAlignmentY(...)」+Cursor+Opaque+Focusableを設定
check2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
check2.setOpaque(false);
check2.setFocusable(false);

  • JTextPane#insertComponent(Component) (Java Platform SE 8)

    コンポーネントは、Component.getAlignmentYによって返された値に従って、テキストベースラインに相対的に配置されます。Swingコンポーネントの場合、JComponent.setAlignmentYメソッドを使うと、この値を簡単に設定できます。たとえば、値を0.75に設定すると、コンポーネントの75%がベースラインの上に、25%がベースラインの下になります。

参考リンク

コメント