Adding JPanel to JFrame

后端 未结 5 1609
长情又很酷
长情又很酷 2021-02-06 04:24

I have a program in which a JPanel is added to a JFrame:

public class Test{

    Test2 test = new Test2();
    JFrame frame = new JFrame();

    Test(){

    ...         


        
5条回答
  •  臣服心动
    2021-02-06 04:31

    Instead of having your Test2 class contain a JPanel, you should have it subclass JPanel:

    public class Test2 extends JPanel {
    
    Test2(){
    
    ...
    
    }
    

    More details:

    JPanel is a subclass of Component, so any method that takes a Component as an argument can also take a JPanel as an argument.

    Older versions didn't let you add directly to a JFrame; you had to use JFrame.getContentPane().add(Component). If you're using an older version, this might also be an issue. Newer versions of Java do let you call JFrame.add(Component) directly.

提交回复
热议问题