swing之JFrame 理解
阿新 • • 發佈:2019-02-11
JFrame可以使用add方法來新增元件,像:
這裡有對應的code:
所以平時我們在add元件(呼叫JFrame.add(Component))的時候,其實是把這些元件新增到內容窗格中(contentPane),更準確的做法是JFrame.getContentPane().add(Component), 由於是JFrame重寫了Add方法,所以直接用JFrame.add(Component), 也就是呼叫的上面的getContentPane再add的呼叫形式。
而當我們檢視api文件的時候,我們發現還有兩個pane可以get,即:
frame.add(child); 這樣子級將被新增到contentPane面板上。內容窗格始終是非 null 的。試圖將其設定為 null 會導致 JFrame 丟擲異常。預設的內容窗格上會設定有BorderLayout管理器。
通常我們在new JFrame()例項的時候,這個頂級容器就為我們分配了兩部分的內容,即:Menu Bar和contentPane. 如下圖:
這裡有對應的code:
/** * <br> * do what you want to do and never stop it. * <br> */ package com.infy.basecompent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuBar; /** * @author Jack * 2012-8-17 * <br> */ public class TopLevelDemo { /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. frame.pack(); frame.setVisible(true); } /** * @param args */ public static void main(String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
所以平時我們在add元件(呼叫JFrame.add(Component))的時候,其實是把這些元件新增到內容窗格中(contentPane),更準確的做法是JFrame.getContentPane().add(Component), 由於是JFrame重寫了Add方法,所以直接用JFrame.add(Component), 也就是呼叫的上面的getContentPane再add的呼叫形式。
而當我們檢視api文件的時候,我們發現還有兩個pane可以get,即: