3
我想在JFrame上绘制JPanel。 JPanel的JFrame背景颜色不同。到目前为止,这个我的代码:JFrame和JPanel的背景颜色不同
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();
}
}
当我运行代码的颜色是红色的。不是红色(JPanel)黄色(JFrame)。如何解决它?
你的代码是否编译,类名'DifferentColor'和构造函数名'GradientColor'不匹配 – Arvind
'JFrame'使用BorderLayout,然后是'JPanel'('this.add(p);')覆盖整个'getContentPane()',你可以使用GridBagLayout或BoxLayout作为JFrame,然后'getContentPane()'的一部分应该在屏幕上可见 – mKorbel