2011-02-01 8 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クラスは、コンテンツとして1つの緑のJPanelを持つJPanelです。 BorderLayoutが設定されている場合、緑色のパネルはパネル内のすべての領域を占有し、PaintComponentメソッドは不要です。

は、あなたのコードに、このメソッドを追加し、あなたはそれが起こるはずです。

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

ありがとう@jzdは理にかなっています。 –

3

ネストされたパネルは、すべてのコンポーネントをカバーしていますので。損傷した領域(再塗りつぶしされる領域)は、子領域がすべての損傷領域をカバーしているため、子領域を通過しています。

関連する問題