2

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);
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jon
  • 193
  • 2
  • 10

1 Answers1

3

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.

Anthony Neace
  • 25,013
  • 7
  • 114
  • 129
  • 1
    Thanks for this. I think I need to read up on how the inheritance of the background transparency affects its sub-components visibility. I would have thought setting the visibility explicitly would have worked. By changing the alpha channel as you say does the job. Cheers. – Jon Oct 09 '12 at 09:59