views:

38

answers:

2

Hi, The code I am using is:

public class Test extends JFrame implements ActionListener {

    private static final Color TRANSP_WHITE =
        new Color(new Float(1), new Float(1), new Float(1), new Float(0.5));
    private static final Color TRANSP_RED =
        new Color(new Float(1), new Float(0), new Float(0), new Float(0.1));
    private static final Color[] COLORS =
        new Color[]{TRANSP_RED, TRANSP_WHITE};
    private int index = 0;
    private JLabel label;
    private JButton button;

    public Test() {
        super();

        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        label = new JLabel("hello world");
        label.setOpaque(true);
        label.setBackground(TRANSP_WHITE);

        getContentPane().add(label);

        button = new JButton("Click Me");
        button.addActionListener(this);

        getContentPane().add(button);

        pack();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(button)) {
            label.setBackground(COLORS[index % (COLORS.length)]);
            index++;
        }
    }

    public static void main(String[] args) {
        new Test();
    }
}

When I click the button to change the labales color the GUI looks like this:

Before: alt text After: alt text

Any ideas why?

+2  A: 

You are giving the JLabel a background that is semi-transparent but you have specified that it is opaque. This means that Swing will not paint the components under it before it provides the JLabel with the Graphics object to use for drawing. The provided Graphics contains junk that it expects the JLabel to overwrite when it draws its background. However when it draws its background it is semi-transparent so the junk remains.

To fix the problem you need to create an extension of JLabel that is not opaque but has an overridden paintComponent method that will draw the background you want.

EDIT: Here's an example:

public class TranslucentLabel extends JLabel {
    public TranslucentLabel(String text) {
        super(text);
        setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        graphics.setColor(getBackground());
        graphics.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(graphics);
    }
}
Russ Hayward
could you provide an example of the paintComponent method?
Aly
+2  A: 

Backgrounds With Transparency provides the solution you accepted, but also provides you with a solution you can use without extending JLabel, which might be of interest.

camickr