日期:2014-05-20  浏览次数:20769 次

Containter类怎么会这样。。(Swing类问题)
昨天我重写了JPanel的paintComponent方法搞了个子类MyComponent  
结果不知道为什么调用MyComponent的setBackground方法却设置不了MyComponent组件的背景色
(希望高手帮忙看看原因,在google上收到一个类似的 但感觉根本没回答问题的真正原因
http://topic.csdn.net/u/20090511/21/097276e4-ede3-4121-8e78-606a819c8c61.html)
下边是我的代码。。
Java code

import javax.swing.*;
import java.awt.*;

public class MySwing {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        SimpleFrame frame = new SimpleFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}

class SimpleFrame extends JFrame {
    public SimpleFrame() {
        Toolkit kit = Toolkit.getDefaultToolkit();
        setBounds(100, 100, kit.getScreenSize().width/2, kit.getScreenSize().height/2);
        getContentPane().setBackground(Color.RED);
        setTitle("Very Cool!!!");
        setResizable(false);
        setBackground(Color.BLACK);
        //setLayout(null);
        Container c = getContentPane();
        //System.out.println("before new");
        MyComponent m = new MyComponent();
        //System.out.println("before new");
        System.out.println(m.isOpaque());
        c.add(m);
        
    }
}
class MyComponent extends JPanel{
    public MyComponent() {
        super.setSize(200,200);
        super.setVisible(true);
        setBackground(Color.YELLOW);
    }
    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        //System.out.println("paintComponent");
        Graphics2D g2 = (Graphics2D)g;
        g2.setPaint(Color.GREEN);
        g.drawString("Very Happy", 100, 100);
        
        Rectangle rect = new Rectangle();
        rect.setBounds(10, 10, 20, 20);
        g2.fill(rect);
    
    }
    /*public void setBackground(Color c) {
        super.setBackground(c);
        System.out.println("background");
    }*/
    /*public void repaint() {
        super.repaint();
        System.out.println("repaint");
    }*/
}




于是我决定查看下JPanel类的JDK 
结果发现JPanel的setBackground方法是继承自JComponent的  
接着我又打开了JCoponent的src文件(源文件)
里边的setBackground方法是这么定义的:
Java code

public void setBackground(Color bg) {
    Color oldBg = getBackground();
    super.setBackground(bg);
    if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
        // background already bound in AWT1.2
        repaint();
    }
    }


里边有一句:
Java code

super.setBackground(bg);


他调用的是父类的setBackground方法
可是JComponent的直接父类是Containter类
可是Containter类没有setBackground方法啊
而Containter类的父类Component倒是有
难道JComponent的:
Java code

super.setBackground(bg);


这句还能调用JComponent的setBackground方法?
不解中。。。。

------解决方案--------------------
Java code
 public void paintComponent(Graphics g) {
        super.paintComponents(g); //注意这里,后面多了个s,是super.paintComponent(g)