[英]Different background color for JFrame and JPanel
I want to draw a JPanel on a JFrame. 我想在JFrame上绘制JPanel。 Background color for JFrame is different for JPanel.
JFrame的背景颜色对于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).
黄色(JFrame)上不是红色(JPanel)。 How to solve it ?
怎么解决?
Your problem is that the JPanel
has the same size then your JFrame
. 您的问题是
JPanel
与JFrame
大小相同。 The reason was explained by Arvind. 原因是Arvind解释的。
Following snippet would assign the JPanel
to the North
region and add a thick blue border around it for demonstration. 以下片段将
JPanel
分配给North
地区,并在其周围添加一个粗蓝色边框用于演示。
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 . 另请参阅Swing教程中有关使用面板的内容 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.