开发者

Why does setting the layout to BorderLayout mean the paintComponent is never called

开发者 https://www.devze.com 2023-02-07 17:27 出处:网络
In the following example program, if you set useBorderlayout to true, the paintComponent method is never called - why?!

In the following example program, if you set useBorderlayout to true, the paintComponent method is never called - why?!

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...");

        Swin开发者_StackOverflow社区gUtilities.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);
            }
        });
    }
}


Because it doesn't need to. The PaintComponentTest class is a JPanel that has one green JPanel as content. When the BorderLayout is set, the green panel takes up all the space in panel and the PaintComponent method is not needed.

Add this method to your code and you should see it happen:

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


Because the nested panel covers all the component. Damaged region (to be repainted) is past to the children because the child bounds cover all the damaged region.

0

精彩评论

暂无评论...
验证码 换一张
取 消