I want to draw a JPanel on a JFrame. Background color for JFrame is different for JPanel. So far, this my code:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DifferentColor extends JFrame{
JPanel p;
GradientColor(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 500));
this.getContentPane().setBackground(Color.yellow);
p = new JPanel();
p.setPreferredSize(new Dimension(400, 400));
p.setBackground(Color.red);
this.add(p);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
// TODO code application logic here
new DifferentColor ();
}
}
WhenI run the code the color is red. Is not red (JPanel) on yellow (JFrame). How to solve it ?
Your problem is that the JPanel
has the same size then your JFrame
. The reason was explained by Arvind.
Following snippet would assign the JPanel
to the North
region and add a thick blue border around it for demonstration.
public void showFrame() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 500));
this.getContentPane().setBackground(Color.yellow);
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(400, 400));
p.setBackground(Color.red);
Border border = BorderFactory.createLineBorder(Color.blue, 10);
border.isBorderOpaque();
p.setBorder(border);
this.add(p, BorderLayout.NORTH);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new DifferentColor().showFrame();
}
Have a look also in the Swing tutorial about use of panels .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.