Rendicahya
Rendicahya

Reputation: 4285

JPanel transparency problem

I have a dark-gray JPanel with a JLabel on it. I set new Color(0, 0, 0, .5f) (tranparent) as the background of the JLabel and I change the text several times using a button. The problem is, everytime the text is changed, the previous text still remains behind the new text. I change the text from "123456789" to "1234567", "12345" and "123". Here is the screenshot:

alt text

How do I get rid of this "shadow"?

Upvotes: 5

Views: 6179

Answers (3)

camickr
camickr

Reputation: 324207

I have a dark-gray JPanel with a JLabel on it. I set new Color(0, 0, 0, .5f) (tranparent)

Swing does not support transparent backgrounds.

Swing expects a component to be either:

  1. opaque - which implies the component will repaint the entire background with an opaque color first before doing custom painting, or
  2. fully transparent - in which case Swing will first paint the background of the first opaque parent component before doing custom painting.

The setOpaque(...) method is used to control the opaque property of a component.

In either case this makes sure any painting artifacts are removed and custom painting can be done properly.

If you want to use tranparency, then you need to do custom painting yourself to make sure the background is cleared.

The custom painting for the panel would be:

JPanel panel = new JPanel()
{
    protected void paintComponent(Graphics g)
    {
        g.setColor( getBackground() );
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(g);
    }
};
panel.setOpaque(false); // background of parent will be painted first

Similar code would be required for every component that uses transparency.

Or, you can check out Background With Transparency for custom class that can be used on any component that will do the above work for you.

Upvotes: 6

evilReiko
evilReiko

Reputation: 20503

try this, maybe it will solve your problem: In actionPeroformed..

public void actionPerformed(ActionEvent e) {
    final JLabel tmpLabel = new JLabel(value[++i]); //change text
    label.setFont(new Font("Times New Roman", 1, 36));
    label.setForeground(new Color(255, 255, 255));
    label.setBackground(new Color(0, 0, 0, .5f));
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setOpaque(true);
    label.setBounds(10, 10, 270, 70);
    label = tmpLabel; //replace the entire label with a new label
}

Upvotes: 2

trashgod
trashgod

Reputation: 205885

This related example also makes the JPanel translucent.

Upvotes: 3

Related Questions