TITLE:JTextAreaの背景に画像を表示

Posted by at 2006-03-06

JTextAreaの背景に画像を表示

`JTextArea`の背景に画像を表示しています。Swing - How can I use TextArea with Background Picture ?のコードを引用しています。

  • &jnlp;
  • &jar;
  • &zip;
CentredBackgroundBorder.png

サンプルコード

class CentredBackgroundBorder implements Border {
  private final BufferedImage image;
  public CentredBackgroundBorder(BufferedImage image) {
    this.image = image;
  }
  @Override public void paintBorder(Component c, Graphics g,
      int x, int y, int width, int height) {
    x += (width-image.getWidth())/2;
    y += (height-image.getHeight())/2;
    ((Graphics2D) g).drawRenderedImage(image, 
      AffineTransform.getTranslateInstance(x,y));
  }
  @Override public Insets getBorderInsets(Component c) {
    return new Insets(0,0,0,0);
  }
  @Override public boolean isBorderOpaque() {
    return true;
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、以下のようにして`JTextArea`の背景に画像を表示しています。

  • 画像を中央に表示するようにした`Borderを作成し、これをViewportBorder`として設定
  • `Viewportに追加したJTextArea`の背景を透明化
    • `textarea.setOpaque(false);`
    • `textarea.setBackground(new Color(0,0,0,0)));`

`Borderを使って背景に画像を表示する方法は、JDesktopPane(参考:JInternalFrameを半透明にする)や、その他のJComponent`でも使用することが出来ます。

参考リンク

コメント

  • `centreは英式のcenter`のこと?らしいです。 -- aterai