ad是我写的一个JPanel的子类:class ad extends JPanel {

public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Line2D.Double Line=new Line2D.Double(10,10,80,40);
g2.setPaint(Color.BLACK);
g2.draw(Line);
}
}
              public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("draw Line");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ad a=new ad();
a.setPreferredSize(new Dimension(150,100));
a.setBackground(Color.blue);//这句没有作用
f.getContentPane().add(a);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new test();
}
但是改成
            public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame("draw Line");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel a=new JPanel();
a.setPreferredSize(new Dimension(150,100));
a.setBackground(Color.blue);//这句就有用了
f.getContentPane().add(a);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new test();
}这是为什么呀?
ad不是继承的JPanel类么,setBackground(...)方法应该可以用的~为什么会出现这样的情况呀?