• 追加された行はこの色です。
  • 削除された行はこの色です。
---
category: swing
folder: AutomaticallyResizeFont
title: Fontサイズをコンポーネントの幅に応じて変更する
tags: [JTextPane, Font]
author: aterai
pubdate: 2011-10-31T15:45:05+09:00
description: JTextPaneのフォントサイズをその幅に応じて自動変更します。
image: https://lh6.googleusercontent.com/-RTjWJaRHh4E/Tq4_8nk91OI/AAAAAAAABEY/mwfxMScDHec/s800/AutomaticallyResizeFont.png
---
* 概要 [#summary]
`JTextPane`のフォントサイズをその幅に応じて自動変更します。

#download(https://lh6.googleusercontent.com/-RTjWJaRHh4E/Tq4_8nk91OI/AAAAAAAABEY/mwfxMScDHec/s800/AutomaticallyResizeFont.png)

* サンプルコード [#sourcecode]
#code(link){{
private final Font font = new Font(Font.MONOSPACED, Font.PLAIN, 12);
private final JTextPane editor = new JTextPane() {
  float font_size = 0f;
  private float font_size = 0f;
  @Override public void doLayout() {
    Insets i = getInsets();
    float f = .08f * (getWidth() - i.left - i.right);
    if (Math.abs(font_size - f) > 1.0e-1) {
      setFont(font.deriveFont(f));
      font_size = f;
    }
    super.doLayout();
  }
};
}}

* 解説 [#explanation]
上記のサンプルでは、`JTextPane#doLayout()`メソッドをオーバーライドし、その幅の変更に応じて使用するフォントのサイズを`Font#deriveFont(float)`メソッドで変更しています。

* 参考リンク [#reference]
- [http://harmoniccode.blogspot.com/2011/10/friday-fun-component-xi.html Harmonic Code: Friday Fun Component XI]

* コメント [#comment]
#comment
#comment