Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JPanel to JFrame

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(){

    ...
    frame.setLayout(new BorderLayout());
    frame.add(test, BorderLayout.CENTER);
    ...

    }

    //main

    ...

    }

    public class Test2{

    JPanel test2 = new JPanel();

    Test2(){

    ...

    }

}

I get an error asking me to change type of 'panel' to 'component'. I do I fix this error? It wants me to do: Component panel = new Component();

like image 317
Anonymous181 Avatar asked May 04 '12 19:05

Anonymous181


People also ask

Can you add a JPanel to a JFrame?

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).

Can you add a JFrame to a JFrame?

You can't put one JFrame inside another. You have a couple of design choices here. You can change your JFrames to JPanels. This is probably the easiest change.

Can I add a JPanel to another JPanel?

The panels connect to one another. So all you need to do us use a panel with a FlowLayout that uses a horizontal gap of 0. Your main code can be something like: JPanel main = new JPanel( new FlowLayout(FlowLayout.


2 Answers

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(){
...
}
like image 125
Andrew Thompson Avatar answered Oct 27 '22 08:10

Andrew Thompson


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();
         }

 }
         );
}

}
like image 41
sabbibJAVA Avatar answered Oct 27 '22 07:10

sabbibJAVA