Reputation: 4057
I have a problem with a JPanel inside another one. I don't know why, but the result is a simple square, but the dimensions aren't correct. Why is that?
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class jj extends JFrame {
private JPanel painel3;
private JPanel painel5;
private Container container;
public jj() {
container = getContentPane();
container.setLayout(null);
painel5 = new JPanel();
painel5.setBackground(Color.red);
painel5.setBounds(120, 110, 100, 120);
painel3 = new JPanel();
painel3.setBackground(Color.white);
painel3.add(painel5);
painel3.setBounds(50, 50, 290, 220);
container.add(painel3);
// frame
setSize(1000, 900);
setLocation(200, 50);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new jj();
}
}
Upvotes: 9
Views: 22608
Reputation: 134
Set the layout of painel3 to null before adding the painel5 panel.
painel3.setLayout(null); painel3.add(painel5);
I recommend to use LayoutManagers.
Upvotes: 0
Reputation: 129093
You need to set the layout for panel3 also to null otherwise the default FlowLayout
is used:
panel3.setLayout(null);
Upvotes: 5
Reputation: 23639
A couple of additional recommendation. Learn to use LayoutManagers. They might have a slight learning curve but it will definitely be worth it. Nice tutorial: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
Also according to the Java Standards, class names should start with a capital letter. Doing this will help others read your code better.
Upvotes: 4
Reputation: 285460
Even better though is to avoid use of null layouts and setBounds/setSize but rather let layout managers help you in laying out your GUI. You can read up on them here: Laying out components in a container
Upvotes: 2