JScrollPane 中 JTextPane 文本后面的静态图像

Static Image behind JTextPane text in JScrollPane

所以我有一个 JScrollPane,我需要滚动(仅垂直)通过居中的自动换行文本。文本后面应该是静态的、不可滚动的部分透明图像。

我的第一个方法是将图像添加到 JScrollPane 中的 JTextPane。由于强制图像滚出其存在的位置,此操作失败。

我的第二种方法是使 JTextPane 的背景透明并在 JLabel 上显示 JTextPane 后面的图像。由于 JTextPane 的背景无法在 JScrollPane 中透明,因此失败。 -现在我可以让它透明,但它会留下损坏、颜色错误和错位的文本以及随机出现在 JTextPane 上的滚动条。

我的第三种方法是改用 JTextArea 并在其后面显示图像。由于 JTextArea 无法居中文本而失败。

我的第四种方法是使用 JLabel 来显示文本。由于 JLabel 无法自动换行而失败。尽管一些人似乎已经 html 解决了这个问题,但 none 仍然有效,因为它们都包裹在不正确的位置。

所以我不确定接下来应该尝试什么,感谢任何帮助。

My second approach was to make the JTextPane's background transparent

是的,这是查看任何背景图片所必需的

Behind the text should be a static, non-scrollable partially transparent image.

您想对滚动窗格的 JViewport 进行自定义绘制以显示图像。

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

public class ViewportBackground
{
    private static void createAndShowUI()
    {
        JTextArea textArea = new JTextArea(10, 30);
//      JTextPane textArea = new JTextPane();
        textArea.setOpaque(false);

        Image image = new ImageIcon("mong.jpg").getImage();

        JViewport viewport = new JViewport()
        {
            @Override
            protected void paintComponent(Graphics g)
            {
                super.paintComponent(g);

                //  add custom painting here. 
                //  For a scaled image you can use:

                g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
            }
        };

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewport(viewport);
        scrollPane.setViewportView( textArea );

        JFrame frame = new JFrame("Viewport Background");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( scrollPane );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}