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();
}
}
8. Can a JPanel be placed inside another JPanel ? A. Yes.
The FlowLayout is a default layout for a JPanel. We can add most of the components like buttons, text fields, labels, tables, lists, trees, etc. to a JPanel. We can also add multiple sub-panels to the main panel using the add() method of Container class.
If you want to let the frame appear at the center of your screen, you can set the location by: frame. setLocationRelativeTo(null); Note that you would want to invoke the above after you set the size (or pack() ) your frame.
These classes are imported and then used in many GUI applications. We use the last, Graphics, to render visuals (e.g., figures, pictures, and even text) in a JPanel that contains the graphics part of a JFrame.
You need to set the layout for panel3 also to null otherwise the default FlowLayout
is used:
panel3.setLayout(null);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With