Is this JPanel code good? Not showing the other JPanel when clicked on the button

前端 未结 2 795
醉话见心
醉话见心 2021-01-28 08:34

How to get that second JPanel to show when someone clicked on the button? The code is giving an error - unknown source. What am I missing?

package Com.global;

i         


        
2条回答
  •  耶瑟儿~
    2021-01-28 09:25

    In your actionPerformed() method, you call panel_1.setVisible(true).

    However, You declare and instantiate panel_1 within the constructor. As soon as you complete execution of the constructor, you go out of scope and the panel_1 reference is lost (panel_1 is available for garbage collection).

    So, by the time you invoke the actionPerformed() method, panel_1 doesn't exists.

    Move the declaration of JPanel panel_1; to the top of your class, along with the other declarations and only then instantiate panel_1 within the constructor: panel_1 = new JPanel();

提交回复
热议问题