Adding JPanel from another class to JPanel in JFrame

后端 未结 4 1687
执念已碎
执念已碎 2020-12-31 16:52

I can\'t get my JFrame from main class to display JPanel from another class. Everything compiles without errors.

JFrameTest.java:

pa         


        
4条回答
  •  别那么骄傲
    2020-12-31 17:23

    First to answer your question, you need to add an instance of your panel to the frame with something like this in your JFrameTest constructor:

    add(new JPanelOne());
    

    You also need to add your button directly to JPanelOne itself:

    public class JPanelOne extends JPanel {   
    
      public JPanelOne() {   
        JButton button = new JButton("test");   
        add(button);   
      }   
    }
    

    Second, I believe there is a problem with these lines of code:

        FlowLayout mainLayout = new FlowLayout(); 
        // snip...
        setLayout(mainLayout); 
    
        JPanel panelMain = new JPanel(mainLayout); 
    

    Each container should have its own instance of a layout manager. Otherwise your GUI will do strange things:

    setLayout(new FlowLayout());
    JPanel panelMain = new JPanel(mainLayout);
    

提交回复
热议问题