2011-02-01 51 views
1

在下面的示例程序中,如果將useBorderlayout設置爲true,那麼paintComponent方法永遠不會被調用 - 爲什麼?爲什麼將佈局設置爲BorderLayout意味着不會調用paintComponent

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

public class PaintComponentTest extends JPanel { 
    private final boolean useBorderLayout; 

    public PaintComponentTest(boolean useBorderLayout){ 
     this.useBorderLayout = useBorderLayout; 
     initialiseComponents(); 
    } 

    public void initialiseComponents(){ 
     setOpaque(true); 
     setBackground(Color.RED); 
     if(useBorderLayout){ 
      //this appears to be the offending line: 
      setLayout(new BorderLayout()); 
     } 
     final JPanel panel = new JPanel(); 
     panel.setOpaque(true); 
     panel.setBackground(Color.GREEN); 
     add(panel, BorderLayout.CENTER); 

    } 
    @Override 
    public void paintComponent(Graphics g){ 
     System.out.println("PaintComponentTest.paintComponent"); 
     super.paintComponent(g); 
    } 

    public static void main(String [] args){ 
     final boolean useBorderLayout = (args.length == 1 && Boolean.parseBoolean(args[0])); 

     System.out.println("Running with"+(useBorderLayout?"":"out")+" BorderLayout as layout manager..."); 

     SwingUtilities.invokeLater(new Runnable(){ 
      public void run(){ 
       final JFrame frame = new JFrame("BorderLayout/PaintComponent test"); 
       frame.setPreferredSize(new Dimension(200, 200)); 
       frame.getContentPane().setLayout(new BorderLayout()); 
       final PaintComponentTest componentTest = new PaintComponentTest(useBorderLayout); 
       frame.getContentPane().add(componentTest); 
       frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       frame.pack(); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 

回答

4

因爲它不需要。 PaintComponentTest類是一個具有一個綠色JPanel作爲內容的JPanel。當設置BorderLayout時,綠色面板佔據面板中的所有空間,並且不需要PaintComponent方法。

此方法添加到您的代碼,你應該看到這一點:

@Override 
    public void paintChildren(Graphics g){ 
     System.out.println("PaintComponentTest.paintChildren"); 
     super.paintChildren(g); 
    } 
+0

感謝@ jzd,這是非常有意義的。 – 2011-02-02 14:05:56

3

因爲嵌套面板涵蓋了所有的組件。受損地區(即將重新粉刷)已經過去,因爲兒童區域覆蓋了所有受損地區。