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