I have a problem with Java JPanels. I would like to put 2 JPanels with different layouts into one JPanel which is also has a layout. Is it even possible to make it work?
BibP()
setLayout(new GridLayout(5, 1)); //The big JPanel
add(new A(), new FlowLayout(4));
add(new B(), new GridLayout(7,2));
Both A and B are classes extends as JPanels and no matter what I changed or commented B is always appears in 1 row. I have 4 elements added to A and 14 to B (JLabels and JTextAreas) and there is not much code in them only the adds and some calculation.
The problem might be in the JFrame where I am trying to put the big JPanel.
JFrame.this.add(new BigP(),BorderLayout.CENTER);
Edit:
public class BigP extends JPanel{
//Labels and TextAres
public class A extends JPanel{
public A(){
setBorder(new EmptyBorder(0, -50, 0, 0));
//get date and add to textareas
//add the label and textareas
}
}
public class B extends JPanel{
public B (){
setBorder(new EmptyBorder(0, -50, 0, 0));
setBackground(Color.red);
//colum longs for text areas less then 5
//add labels and textareas
}
}
public BigP(){
setLayout(new GridLayout(5, 1));
setBorder(new EmptyBorder(3,-160,0,0));
add(new A(), new FlowLayout(4));
add(new B(), new GridLayout(7,2));
}
}
Thanks for helping.
After a few tries:
If I used this:
add(new B(), new GridLayout(7,2));
I get this in B when I printlned the layout:
java.awt.FlowLayout[hgap=5,vgap=5,align=center]
If I set the Layout in B:
setLayout(new GridLayout(7, 2));
The information is correct:
java.awt.GridLayout[hgap=0,vgap=0,rows=7,cols=2]
But there is only 2 JTextAreas vissible where should be 14 elements.
Yes, it's commonly know as compound layouts.
The problem you have is you are trying to supply the
Layout
s as constraints to the current containers layout manager (which in your case, your lucky it wasn't expecting any)...Instead, supply the layout manager directly to the child panels...something like...
Take a look at Laying Out Components Within a Container for more details...
Update with example
Simple runnable example, using labels as place holders.
This
setBorder(new EmptyBorder(3,-160,0,0));
also looks wrong.EmptyBorder
should NEVER have negative valuesYes it is possible to do this. In the following line
I would suggest do
and set the layout of your mainFrame before this