1

拡張するクラスとWindow拡張JFrameするクラスContentがありますJPanel。のオブジェクトが のオブジェクトにContent追加されますWindow

クラスWindow:

public class Window extends JFrame
{   
    private Content content;

    public Window()
    {       
        setTitle("My Window");
        setSize(800, 600);
        setResizable(false);
        setLocationRelativeTo(getParent());
        setDefaultCloseOperation(EXIT_ON_CLOSE);        

        content = new Content(this);

        add(content);

        setVisible(true);
    }

    public static void main(String[] args)
    {
        new Window();
    }
}

クラスContent:

public class Content extends JPanel
{
    public Content(Window w)
    {
        window = w;

        System.out.println(window.getContentPane().getWidth());
    }
}

ここで、コンテンツ ペインの幅を知る必要があります。しかし、window.getContentPane().getWidth()0 を返します。

なぜか教えてくれますか?

4

1 に答える 1

2

getWidth() を呼び出す前に、SetPreferredSize() を使用してから Pack() を使用することが重要です。このコードは、わずかな変更を加えた単なるコードであり、正常に動作します。

public class Window extends JFrame
{   
    private Content content;

    public Window()
    {       
        setTitle("My Window");
        setPreferredSize(new Dimension(800, 600));

        setResizable(false);
        setLocationRelativeTo(getParent());
        setDefaultCloseOperation(EXIT_ON_CLOSE);        
        pack();

        content = new Content(this);

        add(content);

        setVisible(true);
    }

    public static void main(String[] args)
    {
        new Window();
    }
}
public class Content extends JPanel
{
    Window window = null;
    public Content(Window w)
    {
        window = w;
        System.out.println(window.getContentPane().getWidth());
    }
}
于 2015-04-07T01:01:08.903 に答える