• category: swing folder: CentredBackgroundBorder title: JTextAreaの背景に画像を表示 tags: [JTextArea, BufferedImage, Border, JViewport] author: aterai pubdate: 2006-03-06T19:15:08+09:00 description: JTextAreaの背景に画像を表示しています。 description: JTextAreaなどのコンポーネントの背景に、Borderを使って中心揃えした画像を表示します。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTIyAIY_mI/AAAAAAAAATU/GovGMBqjzRo/s800/CentredBackgroundBorder.png

概要

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

概要

JTextAreaなどのコンポーネントの背景に、Borderを使って中心揃えした画像を表示します。Swing - How can I use TextArea with Background Picture ?のコードを引用しています。

サンプルコード

サンプルコード

class CentredBackgroundBorder implements Border {
  private final Insets insets = new Insets(0, 0, 0, 0);
  private final BufferedImage image;
#spanadd

#spanend
  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));
#spanadd

#spanend
  @Override public void paintBorder(
      Component c, Graphics g, int x, int y, int width, int height) {
    int cx = x + (width - image.getWidth()) / 2;
    int cy = y + (height - image.getHeight()) / 2;
    Graphics2D g2 = (Graphics2D) g.create();
    g2.drawRenderedImage(image, AffineTransform.getTranslateInstance(cx, cy));
    g2.dispose();
  }
#spanadd

#spanend
  @Override public Insets getBorderInsets(Component c) {
    return new Insets(0,0,0,0);
    return insets;
  }
#spanadd

#spanend
  @Override public boolean isBorderOpaque() {
    return true;
  }
}
View in GitHub: Java, Kotlin

解説

解説

上記のサンプルでは、以下のようにしてJTextAreaの背景に画像を表示しています。
  • 画像を中央に表示するようにしたBorderを作成し、これをViewportBorderとして設定
  • 画像を中央に表示するようにしたBorderを作成してこれをViewportに設定
  • Viewportに追加したJTextAreaの背景を透明化
    • textarea.setOpaque(false);
    • textarea.setBackground(new Color(0,0,0,0)));
      #spanend
      #spanadd
      textarea.setOpaque(false);
      #spanend
      #spanadd
      textarea.setBackground(new Color(0x0, true)));
      #spanend
      #spanadd
      
  • - Borderを使って背景に画像を表示する方法は、JDesktopPane(参考:JInternalFrameを半透明にする)や、その他のJComponentでも使用することが出来ます。

参考リンク

参考リンク

コメント

コメント