Containter类怎么会这样。。(Swing类问题)
昨天我重写了JPanel的paintComponent方法搞了个子类MyComponent
结果不知道为什么调用MyComponent的setBackground方法却设置不了MyComponent组件的背景色
(希望高手帮忙看看原因,在google上收到一个类似的 但感觉根本没回答问题的真正原因
http://topic.csdn.net/u/20090511/21/097276e4-ede3-4121-8e78-606a819c8c61.html)
下边是我的代码。。
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"); }*/}
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(); } }
super.setBackground(bg);
super.setBackground(bg);
public void paintComponent(Graphics g) { super.paintComponents(g); //注意这里,后面多了个s,是super.paintComponent(g)