Jon
Jon

Reputation: 193

Set the visibility of components within a transparent JFrame

Question: To hide a JPanel which has been added to a transparent JFrame when the button is clicked.

Problem: The JPanel is not correctly hidden, but is still shown with darker colour. Without the alpha channel enabled, it hides ok.

Thanks for your help.

Example Code:

public class TestJFrame extends JFrame {

private JButton mSwitchButton = new JButton("Switch");
private JPanel mPanel = new JPanel();

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

public TestJFrame() {
    setSize(400, 300);      
    getContentPane().setLayout(new BorderLayout());
    this.setBackground(new Color(50, 50, 50, 50));      
    mPanel.setBackground(Color.RED);
    getContentPane().add(mPanel, BorderLayout.CENTER);
    getContentPane().add(mSwitchButton, BorderLayout.SOUTH);        
    mSwitchButton.addMouseListener( new MouseListener() {           
                    ...

        @Override
        public void mouseClicked(MouseEvent arg0) {
            mPanel.setVisible(false);
        }
                    ...
    });     
    pack();
    setVisible(true);
}

Upvotes: 2

Views: 455

Answers (1)

Anthony Neace
Anthony Neace

Reputation: 26023

The darker color has to do with the JFrame -- the JFrame itself is what is not being hidden correctly. Your JPanel is being hidden fine, however, when you set

this.setBackground(new Color(50, 50, 50, 50));

and then remove the JPanel, what you have left is that 50 alpha value. Setting it to:

this.setBackground(new Color(50, 50, 50, 0));

corrected this when I tested it on my machine.

Upvotes: 3

Related Questions