Static Image behind JTextPane text in JScrollPane

Viewed 92

So I have a JScrollPane that I need to scroll (vertically only) through centered word-wrapping text. Behind the text should be a static, non-scrollable partially transparent image.

My first approach was to add the image to the JTextPane in the JScrollPane. This failed due to forcing the image to scroll out of where it exists.

My second approach was to make the JTextPane's background transparent and display the image behind the JTextPane on a JLabel. This failed due to the JTextPane's bacakground not being able to be transparent within the JScrollPane. -Now I could make it transparent, but it would leave behind corrupted, miscolored, and misplaced text along with the scrollbar randomly appearing over the JTextPane.

My third approach was using a JTextArea instead and displaying the image behind the it. This failed due to the JTextArea not being able to center text.

My fourth approach was to use a JLabel to display the text. This failed due to the JLabel not being able to word wrap. Although a few people seemed to have html fixes for this, none worked as they all wrapped at incorrect spots.

So I'm not sure what I should try next, any help is appreciated.

1 Answers

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

Yes, this is necessary to see any background image

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

You want to do custom painting of the JViewport of the scroll pane to display the image.

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();
            }
        });
    }
}
Related