Adding JPanel to JFrame

后端 未结 5 1610
长情又很酷
长情又很酷 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.

    0 讨论(0)
  • 2021-02-06 04:31

    Your Test2 class is not a Component, it has a Component which is a difference.

    Either you do something like

    frame.add(test.getPanel() );
    

    after you introduced a getter for the panel in your class, or you make sure your Test2 class becomes a Component (e.g. by extending a JPanel)

    0 讨论(0)
  • 2021-02-06 04:32
    Test2 test = new Test2();
    ...
    frame.add(test, BorderLayout.CENTER);
    

    Are you sure of this? test is NOT a component! To do what you're trying to do you should let Test2 extend JPanel !

    0 讨论(0)
  • public class Test{
    
    Test2 test = new Test2();
    JFrame frame = new JFrame();
    
    Test(){
    ...
    frame.setLayout(new BorderLayout());
    frame.add(test, BorderLayout.CENTER);
    ...
    }
    
    //main
    ...
    }
    
    //public class Test2{
    public class Test2 extends JPanel {
    
    //JPanel test2 = new JPanel();
    
    Test2(){
    ...
    }
    
    0 讨论(0)
  • 2021-02-06 04:52

    do it simply

    public class Test{
        public Test(){
            design();
        }//end Test()
    
    public void design(){
        JFame f = new JFrame();
        f.setSize(int w, int h);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
        JPanel p = new JPanel(); 
        f.getContentPane().add(p);
    }
    
    public static void main(String[] args){
         EventQueue.invokeLater(new Runnable(){
         public void run(){
             try{
                 new Test();
             }catch(Exception e){
                 e.printStackTrace();
             }
    
     }
             );
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题