changing background on JLabel shifts components

Posted by Aly on Stack Overflow See other posts from Stack Overflow or by Aly
Published on 2010-03-21T15:57:07Z Indexed on 2010/03/21 16:01 UTC
Read the original article Hit count: 415

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about swing