1

在下面的示例程序中,如果将 useBorderlayout 设置为 true,则永远不会调用 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

2 回答 2

4

因为不需要。PaintComponentTest 类是一个以绿色 JPanel 作为内容的 JPanel。当设置了 BorderLayout 时,绿色面板占据了面板中的所有空间,不需要 PaintComponent 方法。

将此方法添加到您的代码中,您应该会看到它发生:

    @Override
    public void paintChildren(Graphics g){
        System.out.println("PaintComponentTest.paintChildren");
        super.paintChildren(g);
    }
于 2011-02-01T12:52:01.913 回答
3

因为嵌套面板覆盖了所有组件。损坏的区域(要重新绘制)对孩子来说是过去的,因为孩子的边界覆盖了所有的损坏区域。

于 2011-02-01T12:53:41.830 回答