Reputation: 21
I am trying to insert a jpanel inside a jframe without using any netbeans drag/drop methods. The problem I encountered is when I give a specific color to Jpanel the same color adheres to entire JFrame. Please help me solve this.
This is my code:
package lookandfeel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
public class LookandFeel {
public static void main(String[] args) {
JFrame window =new JFrame();
JPanel P1=new JPanel();
window.add(P1);
window.setExtendedState(window.MAXIMIZED_BOTH);
window.setResizable(false);
P1.setSize(300, 200);
// window.setLayout(new BorderLayout());
// window.add(P1, BorderLayout.CENTER);
for (Component comp:window.getContentPane().getComponents()) {
if (comp == P1) {
comp.setBackground(Color.DARK_GRAY);
}
else {
comp.setBackground(Color.red);
}
}
window.setUndecorated(true);
window.setVisible(true);
window.getContentPane().setBackground(Color.CYAN);
}
}
Upvotes: 0
Views: 80
Reputation:
BorderLayouts attempt to fill all available space in the JFrame with the given components. Since you only have one single JPanel, that panel fills the entire space.
BorderLayout is the default layout for all JFrames, unless otherwise stated.
Click here to see a visual of different Layouts.
The above link will give you a visual representation of different layouts and how they operate. If you notice, the BorderLayout at the top of the page has absolutely no space left in the window - it's all being taken up by the buttons. The same thing is happening with your JPanel.
You can override the default layout with the method setLayout on your JFrame, such as:
window.setLayout(new GridLayout(0,2));
As stated before, variable naming conventions for Java should be in camelCase (or mixedCase), wherein the first word of the variable is lowercased and all other words capitalized.
Upvotes: 1
Reputation: 57421
The P1 (btw it's better to name variables starting lowercase) fill entire content pane (because it's added to content pane and default layout is BorderLayout which tries to fill all available space).
So P1.setSize(300, 200);
is futile
Upvotes: 3