Java Swing How to - Use an image as JTextArea background








Question

We would like to know how to use an image as JTextArea background.

Answer

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/*  w  ww.ja va2 s  .c  o  m*/
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main {

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(new MyTextArea()));
        frame.pack();
        frame.setVisible(true);
      }
    });
  }
}

class MyTextArea extends JTextArea {
  private BufferedImage image;
  public MyTextArea() {
    super(20, 20);
    try {
      image = ImageIO.read(new File("yourImage.png"));
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
  @Override
  public boolean isOpaque() {
    return false;
  }
  @Override
  protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setColor(getBackground());
    g2d.fillRect(0, 0, getWidth(), getHeight());
    if (image != null) {
      int x = getWidth() - image.getWidth();
      int y = getHeight() - image.getHeight();
      g2d.drawImage(image, x, y, this);
    }
    super.paintComponent(g2d);
    g2d.dispose();
  }
}