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

        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);
            }
        });
    }
}
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top