Java Swing How to - Add Background Image to JTextPane








Question

We would like to know how to add Background Image to JTextPane.

Answer

import java.awt.Color;
import java.awt.Graphics;
//from  www  .jav a 2 s  .co  m
import javax.swing.JFrame;
import javax.swing.JTextPane;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    MyTextPane textPane = new MyTextPane();
    frame.add(textPane);

    frame.pack();
    frame.setVisible(true);
  }
}

class MyTextPane extends JTextPane {
  public MyTextPane() {
    super();
    setText("Hello World");
    setOpaque(false);
    setBackground(new Color(0, 0, 0, 0));
  }

  @Override
  protected void paintComponent(Graphics g) {
    g.setColor(Color.GREEN);
    g.fillRect(0, 0, getWidth(), getHeight());

    // uncomment the following to draw an image
    // Image img = ...;
    // g.drawImage(img, 0, 0, this);

    super.paintComponent(g);
  }
}