JTextPane中的背景图片

Niv*_*vas 3 java swing jtextpane

如何将背景图像设置为JTextPane - 某种水印.

我尝试了这个选项 - 创建一个JTextPane的子类,并使用paint方法绘制图像.但随后文本显示在图像"下方"而不是上方.

有没有"标准"或"众所周知"的方法来做到这一点?

(顺便说一下,我尝试过(傻傻的东西?)使内容类型为"text/html",并将图像设置为a的背景图像,<div>但它没有帮助.)

Ste*_*eod 7

这是一个有效的例子:

import javax.swing.*;
import java.awt.*;

public class ScratchSpace {

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

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

    private static class MyTextPane extends JTextPane {
        public MyTextPane() {
            super();
            setText("Hello World");
            setOpaque(false);

            // this is needed if using Nimbus L&F - see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6687960
            setBackground(new Color(0,0,0,0));
        }

        @Override
        protected void paintComponent(Graphics g) {
            // set background green - but can draw image here too
            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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

需要注意的重要事项:

  1. 你的组件不能是不透明的...所以setOpaque(false);

  2. 覆盖paintComponent(Graphics g),而不是paint.

  3. 在调用super.paintComponent(g)之前用图像或绘图绘制背景;

如果你想掌握这些东西,我建议阅读"肮脏的富客户",这本书都是关于如何根据自己的意愿弯曲Swing.