JLabel transparency problem

Posted by Rendicahya on Stack Overflow See other posts from Stack Overflow or by Rendicahya
Published on 2011-01-04T05:14:43Z Indexed on 2011/01/04 6:53 UTC
Read the original article Hit count: 206

Filed under:
|
|
|

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"? Here's the code:

public class TransparentJLabel extends JFrame {

private int i = 0;
private String[] value = {"123456789", "1234567", "12345", "123", "1"};

public TransparentJLabel() {
    setSize(300, 160);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setLayout(null);

    JPanel panel = new JPanel();
    panel.setBackground(new Color(102, 102, 102));
    panel.setLayout(null);
    panel.setBounds(0, 0, 300, 160);

    final JLabel label = new JLabel();
    label.setText(value[0]);
    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);

    JButton button = new JButton();
    button.setText("Change");
    button.setBounds(100, 90, 90, 25);
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            label.setText(value[++i]);
        }
    });


    panel.add(label);
    panel.add(button);
    add(panel);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        public void run() {
            new TransparentJLabel().setVisible(true);
        }
    });
}

}

© Stack Overflow or respective owner

Related posts about java

Related posts about swing