Java – what are JPanel, JFrame, jlayeredpane and jrootpane
I am a novice in Java. When reading, I encountered various frameworks and panels. What is the confusion between JFrame, jlayeredpane, jrootpane and jpannel? The difference between them is that JFrame and JPanel can be used in a single class at the same time
Solution
Look at the pictures here
From the German java tutorial page
Some details
>JFrame is a window, which is displayed as the top-level window of the operating system. > JFrame consists of multiple functional elements For example, one can reduce the burden of implementing tooltips correctly: layeredpane In addition, tooltips are always above everything else. > Contentpane is the wisest place to place the main content. > JPanel is a general container The number one course you use to put buttons and forms into
The official swing tutorial summarizes the design well
Let's take 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 above code will generate a frame, but it is not really available:
Make it bigger just to reveal the title:
JFrame jFrame = new JFrame("Hi!"); jFrame.setSize(200,50); jFrame.setVisible(true);
result:
Now let's see if we can add any components to the framework Let's add a tag – in swing, it is implemented by the jlabel class:
JFrame jFrame = new JFrame("Hi!"); jFrame.setSize(200,100); JLabel label = new JLabel("Hello Swing!"); jFrame.add(label); jFrame.setVisible(true);
OK, what did we do? Add jlabel to JFrame If you are going to look at swing code, JFrame The add () method adds the component to the contentpane internally 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 whether the contentpane is implemented internally by JPanel In 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; }