簡體   English   中英

在添加框架內容時獲取空指針異常

[英]Getting null pointer exception in adding frame content

在Swing的JFrame中添加內容期間,出現空指針異常。

    public static void createAndShowGUI() {
    //Create and set up the window.
    frame = new JFrame("Data Entry Application");
    //Set up the content pane.
    // frame = new JFrame();
    addComponentsToPane(frame.getContentPane());  // null pointer exception in this line
     }

 public static void addComponentsToPane(Container pane) {
    if (RIGHT_TO_LEFT) {
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }

    Border blackline, raisedetched = null, loweredetched,
            raisedbevel = null, loweredbevel, empty, orangeline, redline, greenline, blueline;
    blackline = BorderFactory.createLineBorder(Color.black);
    orangeline = BorderFactory.createLineBorder(Color.ORANGE);
    redline = BorderFactory.createLineBorder(Color.RED);
    greenline = BorderFactory.createLineBorder(Color.GREEN);
    blueline = BorderFactory.createLineBorder(Color.blue);

    JButton button;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    if (shouldFill) {
        //natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
    }

    /* Header Section start*/
    /* Username and designation starts */
    JPanel p_username = new JPanel();
    p_username.setMinimumSize(new Dimension(140, 30));
    l_username = new JLabel(Login.login_username);
    l_designation = new JLabel("Data Entry User");

    JPanel t9 = new JPanel(new GridLayout(0, 1));
    t9.add(l_username);
    t9.add(l_designation);
    t9.setPreferredSize(new Dimension(140, 30));
    p_username.add(t9);
   c.fill = GridBagConstraints.NORTH;
    c.gridx = 0;
    c.gridy = 0;
    c.ipady = 25;
    c.insets = new Insets(0, 10, 0, 0);
    pane.add(p_username, c);
    /* Username and designation end */
  }

提出一些想法。

我模擬了您的addComponentsToPane()方法,向您展示了問題所在:

private static void addComponentsToPane(Container container)
{
    System.out.println("Is container null? " + container == null);
    JPanel panel = null;
    container.add(panel);
}

調用此方法將產生以下輸出:

false
Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1091)
    at java.awt.Container.add(Container.java:415)
    at FrameDemo.addComponentsToPane(FrameDemo.java:33)
    at FrameDemo.createAndShowGUI(FrameDemo.java:25)
    at FrameDemo.main(FrameDemo.java:14)

如果您閱讀Javadoc,則從結果輸出中可以看到, getContentPane()方法不會返回null。 我的第二行聲明了一個JPanel,但是沒有實例化該對象,然后我嘗試將其添加到內容窗格中。 在我的情況下,這導致NullPointerException

我的結論 :您正在向容器中添加尚未正確實例化的組件。 實際上,如果您閱讀了Container.add(comp)方法的Javadoc,它指出如果comp為null,則此方法將引發NullPointerException 檢查您要添加到其中的所有組件,然后可以找出其余的組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM