Why must I use getContentPane() instead of this keyword as a parameter argument for BoxLayout when setting a JFrame's layout to BoxLayout. To give a JPanel a BoxLayout, I must use this as a parameter.
I think this is because a JFrame has several layers or parts, which are the glass pane, layered pane, content pane, and menu bar. So the this keyword refers to the JFrame, but it does not refer to the content pane which we want to have a layout manager configured. That is why we invoke getContentPane() instead. I read that the content pane of a JFrame is actually a JPanel.
To summarize: BoxLayout's target parameter accepts JPanels but not JFrame, but JFrame's content pane is a 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));
}
}
Does a JPanel have multiple panes like a JFrame? What is the actual reason that I must use getContentPane()?
When the compiler says that BoxLayout can't be shared, does that mean that BoxLayout can not be shared between the multiple panes that compose a JFrame?