Search code examples
javaimageuser-interfacebufferedimagejtextpane

Java: JTextPane isn't loading transparent?


I have a class UITextPane that extends JTextPane, and overrides the paintComponent(g)method, like so:

package com.ritcat14.GotYourSix.graphics.UI;

import com.ritcat14.GotYourSix.util.ImageUtil;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JTextPane;

public class UITextPane extends JTextPane {

    private BufferedImage img;

    public UITextPane() {
        img = ImageUtil.getImage("/ui/panels/helpBackground.png");
    }

    @Override
    public void paintComponent(Graphics g) {
        g.drawImage(img,0,0,null);
        super.paintComponent(g);
    }
}

Then in my Game.javaclass, I create and add the component to the JFrame using GridBagConstraintsas such:

game.textPane = new UITextPane();
    game.textPane.setEditable(false);
    game.textPane.setForeground(new Color(0xffC20F1B));
    game.textPane.setBackground(new Color(1,1,1, (float) 0.01)); //Set transparent so we can see the text

    //create and set font
    ....

    JScrollPane sp = new JScrollPane(game.textPane);
    sp.setPreferredSize(new Dimension(400,400));
    c.anchor = GridBagConstraints.LINE_END;
    game.frame.add(sp, c);

The textPane.paintComponent(g) is called every time the game's render method is called.

My issue: The image I have stored is simply a 400x400transparent image that I am drawing to the JTextPanein the UITextPane class. However, the result looks like the following:

enter image description here

And after singing in, the background goes black like so:

enter image description here

Any ideas what I'm doing wrong / not doing? Thanks


Solution

  • Some LaF don't respect background property. Anyway, you should use setOpaque to achieve what you want.

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame mainFrame = new JFrame("test");
                mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                //Opaque (default behaviour)
                Container pane = mainFrame.getContentPane();
                JTextPane jtp1 = new JTextPane();
                jtp1.setOpaque(true);
                jtp1.setText("this JTextPane is not transparent");
                jtp1.setEditable(false);
    
                //Not opaque (ie transparent)
                JTextPane jtp2 = new JTextPane();
                jtp2.setOpaque(false);
                jtp2.setText("this JTextPane is transparent");
                jtp2.setEditable(false);
    
                pane.setLayout(new FlowLayout());
                pane.setBackground(Color.LIGHT_GRAY);
                pane.add(jtp1);
                pane.add(jtp2);
                mainFrame.pack();
                mainFrame.setVisible(true);
            }
        });
    }