java JComponent背景画像

JComponentには背景画像を表示する標準機能がない。
JComponentの派生クラスを作り、paintComponentをオーバライドし、自力でイメージを描画する必要がありそうだ。
いちいち派生クラスを作らないで、部品化することはできないかと、ほんのちょっとだけ思案してみたが、有力なジェネリックスも動的でないため、できそうにない。
しかたなくヘルパークラスにしてみた。
以下がその背景画像付きJComponentのヘルパーだ。

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

public class ImageBackgroundComponent {

  public static final int STRETCH = 0;
  public static final int TILED = 1;
  public static final int ACTUAL = 2;
  private Image _img;
  private int _style = ACTUAL;
  private Color _bgcolor = null;
  private float _halign = Component.CENTER_ALIGNMENT;
  private float _valign = Component.CENTER_ALIGNMENT;

  public ImageBackgroundComponent(Image img, int style) {
    this._img = img;
    this._style = style;
  }

  public ImageBackgroundComponent(Image img, int style, 
            float halign, float valign, Color bgcolor) {
    this._img = img;
    this._style = style;
    this._halign = halign;
    this._valign = valign;
    this._bgcolor = bgcolor;
  }

  public void paintComponent(Graphics g, JComponent parent) {
    if(this._img != null) {
      int fw = parent.getWidth();
      int fh = parent.getHeight();
      if(this._bgcolor != null) {
        g.setColor(this._bgcolor);
        g.fillRect(0, 0, fw, fh);
      }
      ImageIcon icon = new ImageIcon(this._img);
      if(icon != null) {
        int iw = icon.getIconWidth();
        int ih = icon.getIconHeight();

        if(this._style == TILED) {
          for(int y = 0; y < fh; y += ih) {
            for(int x = 0; x < fw; x += iw) {
              g.drawImage(icon.getImage(), x, y, 
                                           iw, ih, parent);
            }
          }
        } else {
          int w = (this._style == STRETCH)? fw: iw;
          int h = (this._style == STRETCH)? fh: ih;
          int x = (int)Math.floor(fw * this._halign) - w / 2;
          int y = (int)Math.floor(fh * this._valign) - h / 2;
          g.drawImage(icon.getImage(), x, y, w, h, parent);
        }
      }
    }
  }
}

使い方は以下。
残念ながら派生が必要だ。

public class ImageDesktopPane extends JDesktopPane {

  static final long serialVersionUID = 0L;
  private ImageBackgroundComponent imbcomp;

  public ImageDesktopPane(Image img) {
    this.imbcomp = new ImageBackgroundComponent(img,
                      ImageBackgroundComponent.ACTUAL);
    // When using a tile pattern
    //this.imbcomp = new ImageBackgroundComponent(img,
    //                 ImageBackgroundComponent.TILED);
  }

  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.imbcomp.paintComponent(g, this);
  }
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です