JTextAreaの背景に画像を表示
Total: 19851, Today: 1, Yesterday: 3
Posted by aterai at
Last-modified:
Summary
JTextAreaなどのコンポーネントの背景に、Borderを使って中心揃えした画像を表示します。Swing - How can I use TextArea with Background Picture ?のコードを引用しています。
Screenshot

Advertisement
Source Code Examples
class CentredBackgroundBorder implements Border {
private final Insets insets = new Insets(0, 0, 0, 0);
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) {
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();
}
@Override public Insets getBorderInsets(Component c) {
return insets;
}
@Override public boolean isBorderOpaque() {
return true;
}
}
View in GitHub: Java, KotlinDescription
上記のサンプルでは、以下のようにしてJTextAreaの背景に画像を表示しています。
- 画像を中央に表示するようにした
Borderを作成してこれをViewportに設定 Viewportに追加したJTextAreaの背景を透明化textarea.setOpaque(false); textarea.setBackground(new Color(0x0, true)));
Borderを使って背景に画像を表示する方法はJDesktopPane(参考: JInternalFrameを半透明にする)や、その他のJComponentでも使用可能