Background Image in JTextPane

How to set a background image on JTextPane - some kind of watermark.

I tried this option - creating a JTextPane child class and using the drawing method to draw the image. But then the text is displayed below the image than shown above.

Is there any “standard” or “well-known” way to do this?

(By the way, I tried (is something stupid?), Creating the content type "text / html" and setting the image as the background image <div>, but that did not help.)

+3
source share
3 answers

Here is a working example:

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

It is important to note:

  • ... setOpaque (false);

  • paintComponent ( g), .

  • , super.paintComponent();

, "Filthy Rich Clients", , Swing .

+7

.

  public void paint(Graphics g)
  {
        g.setXORMode(Color.white);
        g.drawImage(image,0, 0, this);
        super.paint(g);
  }

, , .

+1

Hmm., JFrame/JPanel, JTextPane,.. JTextPane .

+1

Source: https://habr.com/ru/post/1739259/


All Articles