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 クラスは、コンテンツとして 1 つの緑色の 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 に答える