在将 JFrame 的布局设置为 BoxLayout 时,为什么必须使用 getContentPane() 而不是 this 关键字作为 BoxLayout 的参数。要为 JPanel 提供 BoxLayout,我必须使用 this 作为参数。
我认为这是因为 JFrame 有多个层或部分,它们是玻璃 Pane 、分层 Pane 、内容 Pane 和菜单栏。因此 this 关键字引用 JFrame,但它并不引用我们想要配置布局管理器的内容 Pane 。这就是我们调用 getContentPane() 的原因。我读到 JFrame 的内容 Pane 实际上是 JPanel。
总结一下:BoxLayout 的目标参数接受 JPanel,但不接受 JFrame,但 JFrame 的内容 Pane 是 JPanel。
class MyFrame1 extends JFrame {
public MyFrame1() {
// This line does not work, why?
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
}
class MyFrame2 extends JFrame {
public MyFrame2() {
// This line works
setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
}
}
class MyPanel extends JPanel {
public MyPanel() {
// JPanel uses "this" keyword
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
}
JPanel 是否像 JFrame 一样具有多个 Pane ?我必须使用 getContentPane() 的实际原因是什么?
当编译器说 BoxLayout 不能共享时,是否意味着 BoxLayout 不能在组成 JFrame 的多个 Pane 之间共享?
最佳答案
JFrame
是一个 Container
,但它不是 Container
"that needs to be laid out."相反,由 getContentPane()
返回的 Container
是可以使用 BoxLayout
实例的容器。或者考虑下面使用 Box
的变体,“使用 BoxLayout
对象作为其布局管理器的轻量级容器。”
Box b = Box.createVerticalBox();
b.add(new JLabel("Test"));
f.setContentPane(b);
经测试:
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
/** @see http://stackoverflow.com/a/23159430/230513 */
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box b = Box.createVerticalBox();
b.add(new JLabel("Test"));
f.setContentPane(b);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Test().display();
}
});
}
}
关于java - 为什么在为 JFrame 设置 BoxLayout 时必须使用 getContentPane() 而不是 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23153233/