2015-12-15 184 views
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)。如何解决它?

+0

你的代码是否编译,类名'DifferentColor'和构造函数名'GradientColor'不匹配 – Arvind

+0

'JFrame'使用BorderLayout,然后是'JPanel'('this.add(p);')覆盖整个'getContentPane()',你可以使用GridBagLayout或BoxLayout作为JFrame,然后'getContentPane()'的一部分应该在屏幕上可见 – mKorbel

回答

-1

您的问题是JPanel与您的JFrame尺寸相同。 Arvind解释了这个原因。

以下片段会将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(); 
} 

看一看也在Swing tutorial about use of panels