Component的背景色设置问题

来源:百度知道 编辑:UC知道 时间:2024/05/24 15:49:06
import java.awt.*;
import javax.swing.*;
public class color{
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setTitle("My");
frame.setSize(300,200);
MyComponent panel=new MyComponent();
frame.add(panel);
panel.setBackground(Color.YELLOW);
frame.setVisible(true);
}
}
class MyComponent extends JComponent{
}

为什么不能显示出黄色呢
而用JPanel取代JComponent 就可以显示出 为什么

这是因为您的frame是一个JFrame,而JFrame本来就包含一个内置的容器。你可以通过修改这个内置的容器来改变颜色。您可以使用下面的语句来获取frame的内置容器:
Container c=frame.getContentPane();
然后改变c的颜色:
c.setBackground(Color.YELLOW);
这样就可以了。
全部的代码如下:
import java.awt.*;
import javax.swing.*;
public class color{
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setTitle("My");
frame.setSize(300,200);
Container c=frame.getContentPane();
c.setBackground(Color.YELLOW);
frame.setVisible(true);
}
}