Swing programs implement their windows with JFrame objects. The JFrame class is a subclass of the AWT Frame class. It also adds some features unique to Swing. Very similar to the use of Frame. The only difference is that you can't add components to a JFrame. You can either add components to the content pane of JFrame, or provide a new content pane.
Differences between panels and top-level containers: panels cannot exist independently and must be added to the inside of other containers (panels can be nested).
JFrame has a Content Pane, and all components that can be displayed in the window are added to this Content Pane. JFrame provides two methods: getContentPane and setContentPane are used to obtain and set their Content Pane.
There are two ways to add components to JFrame:
1) Use the getContentPane () method to obtain the content panel of JFrame, and then add components to it: frame. getContentPane ().add(childComponent)
2) Create an intermediate container such as Jpanel or JDesktopPane, add the components to the container, and use the setContentPane() method to set the container as the content panel of the JFrame:
JPanel contentPane = new JPanel(); ...//Add other components to Jpanel; frame.setContentPane(contentPane); //Set the contentPane object to the frame's content panel
Example program:
import java.awt.*; import javax.swing.*; public class JFrameWithPanel { public static void main(String[] args) { JFrame frame = new JFrame("Frame With Panel"); Container contentPane = frame.getContentPane(); contentPane.setBackground(Color.CYAN); // Set the background of the JFrame instance to blue-green JPanel panel = new JPanel(); // Create an instance of JPanel.setBackground(Color.yellow); // Set the background of JPanel's instance to yellow JButton button = new JButton("Press me"); panel.add(button); // Add JButton instance to JPanel contentPane.add(panel, BorderLayout.SOUTH); // Add JPanel instance to the south side of JFrame.setSize(300, 200); frame.setVisible(true); } }screenshot:
Summarize
The above is the entire content of this article about the example analysis of the method of adding and setting JPanel in JFrame. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!