i am new to java while reading i came across various frames and panels,confused between JFrame ,JLayeredPane ,JRootPane and JPannel what is diffrence between them is it possible to use both JFrame and JPanel in single class.
Take a look at the picture here
from the German Java Tutorial page.
Some details
The official Swing tutorial sums up the design very well.
Let's do a minimal example:
import javax.swing.JFrame;
public class SomeFrame {
public static void main(String [] as) {
// let's make it as simple as possible
JFrame jFrame = new JFrame("Hi!");
jFrame.setVisible(true);
}
}
The code above would produce a Frame, but not really usable:
Let's make it a little bigger, only to expose the title:
JFrame jFrame = new JFrame("Hi!");
jFrame.setSize(200, 50);
jFrame.setVisible(true);
Result:
Now, lets see if we can add any component into the frame. Let's add a label - in Swing it's realized by the class JLabel
:
JFrame jFrame = new JFrame("Hi!");
jFrame.setSize(200, 100);
JLabel label = new JLabel("Hello Swing!");
jFrame.add(label);
jFrame.setVisible(true);
Ok, so what we have done? Added the JLabel
into the JFrame
. If You'll look into the Swing code, internally the JFrame.add()
method adds the component into the ContentPane. So the above code is equivalent to:
JFrame jFrame = new JFrame("Hi!");
jFrame.setSize(200, 100);
JLabel label = new JLabel("Hello Swing!");
jFrame.getContentPane().add(label); // <----
jFrame.setVisible(true);
You can check by yourself that the ContentPane is realized internally by a JPanel. It's in the Swing code:
// this invocation...
JFrame jFrame = new JFrame("Hi!");
// effectively invokes following methods:
public JFrame(String title) throws HeadlessException {
// ...
frameInit();
}
protected void frameInit() {
// ...
setRootPane(createRootPane());
// ...
}
protected JRootPane createRootPane() {
JRootPane rp = new JRootPane();
// ...
}
public JRootPane() {
setGlassPane(createGlassPane());
setLayeredPane(createLayeredPane());
setContentPane(createContentPane());
// ...
}
protected Container createContentPane() {
JComponent c = new JPanel(); // <----
// ...
return c;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With