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(...)方法应该可以用的~为什么会出现这样的情况呀?

解决方案 »

  1.   

    你ad继承JPanel,又没有重载setBackground方法,所以子类当然不存在这个方法了。
    而你直接实例化JPanel类,这个类里面本来就有setBackground方法,当然就可以引用了。
    不矛盾吧,楼主应该再看一下面向对象!
      

  2.   

    为什么要重载setBackground(..)方法呢?JPanel类里面有这个方法的说~
      

  3.   

    父类的 paint 方法被你覆盖了public void paint(Graphics g) { 
    super.paint(g);  // 这样子就又行了
    Graphics2D g2 = (Graphics2D)g; 
    Line2D.Double Line=new Line2D.Double(10,10,80,40); 
    g2.setPaint(Color.BLACK); 
    g2.draw(Line); 
      

  4.   

    请问为什么加上了super.paint方法就可以了呢  ?这方法跟setBackground方法有什么关系?为什么我覆盖了
    paintComponent方法却不行呢?(覆盖的方法里调用了super.Background())