3

私の主な問題は、JFrameをセットアップするときの次のコードにあります。

public Frame(){
  JPanel panel = new JPanel();
  add(panel);
  panel.setPreferredSize(new Dimension(200, 200));

  pack(); // This is the relevant code
  setResizable(false); // This is the relevant code

  setVisible(true);
}

次の印刷ステートメントを使用すると、パネルの寸法に誤りがあります。

System.out.println("Frame: " + this.getInsets());
System.out.println("Frame: " + this.getSize());
System.out.println("Panel: " + panel.getInsets());
System.out.println("Panel: " + panel.getSize());

Output:
Frame: java.awt.Insets[top=25,left=3,bottom=3,right=3]
Frame: java.awt.Dimension[width=216,height=238]
Panel: java.awt.Insets[top=0,left=0,bottom=0,right=0]
Panel: java.awt.Dimension[width=210,height=210]

関連するコードを次のように変更すると、問題が修正されることがわかりました。

public Frame(){
  JPanel panel = new JPanel();
  add(panel);
  panel.setPreferredSize(new Dimension(200, 200));

  setResizable(false); // Relevant code rearranged
  pack(); // Relevant code rearranged

  setVisible(true);
}

これにより、パネルの正しい寸法が生成されます(以前と同じ印刷ステートメントを使用)。

Frame: java.awt.Insets[top=25,left=3,bottom=3,right=3]
Frame: java.awt.Dimension[width=206,height=228]
Panel: java.awt.Insets[top=0,left=0,bottom=0,right=0]
Panel: java.awt.Dimension[width=200,height=200]

いくつかのドキュメントを調べましたが、これらの10ピクセルがどこから来ているのかわかりませんでした。なぜこれが当てはまるのか誰かが知っていますか?

4

1 に答える 1

6

JFrameはFrameから派生しており、のFrameソースコードに次のsetResizable(...)コメントが表示されます。

    // On some platforms, changing the resizable state affects
    // the insets of the Frame. If we could, we'd call invalidate()
    // from the peer, but we need to guarantee that we're not holding
    // the Frame lock when we call invalidate().

pack() このため、を呼び出した後に呼び出すのは理にかなっていますsetResizable(false)

于 2013-02-20T19:28:54.717 に答える