Aly Abed Aly Abed - 4 months ago 25
Java Question

JPanel visibility

When a

JPanel
is set to not visible is it still "touchable"? As in I have a
JPanel
on my frame and the panel has buttons for instance. If I set the panel to NOT be visible if I press on where a button is if it were visible, would the button still function?

I am asking to better understand the
setVisible
not actually trying to achieve what is being said above.

Answer

I don't know whether you have tested what @Marvin Jude said. But for my example, the instance is untouchable when its parent container is invisible.

  1. Use panel.setVisible(true); or panel.setVisible(true); to change the visibility of JPanel.
  2. The button's listener is not triggered if MainPanel is not visible.

See code below.

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.*;

    public class MyFrame extends JFrame{

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public MyFrame(){
            MainPanel panel = new MainPanel();
            add(panel,BorderLayout.CENTER);
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
            pack();
            panel.setVisible(true);
        }

        class MainPanel extends JPanel{

            /**
             * 
             */
            private static final long serialVersionUID = 1L;
            public MainPanel(){
                JButton button = new JButton("I am a button");
                add(button);
                button.addActionListener(new ActionListener(){

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("JButton is clicked...");
                    }
                });
            }
        }

        public static void main(String args[]){
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    MyFrame myFrame = new MyFrame();
                    myFrame.setVisible(true);
                }
            };
            SwingUtilities.invokeLater(runnable);
        }
    }