簡體   English   中英

JFrame和JPanel的不同背景顏色

[英]Different background color for JFrame and JPanel

我想在JFrame上繪制JPanel。 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 ();
  }
}

當我運行代碼時,顏色為紅色。 黃色(JFrame)上不是紅色(JPanel)。 怎么解決?

您的問題是JPanelJFrame大小相同。 原因是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教程中有關使用面板的內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM