2015-12-15 143 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