首页 > 解决方案 > 我们可以在其他面板中添加面板吗?如果是,那么我的代码有什么问题

问题描述

我正在尝试制作一个非常简单的时间管理器,当我编译它时显示错误。我无法在我的代码中找到导致错误的错误。

JPanel otherPanel = new JPanel();
otherPanel.add(BorderLayout.WEST, timingsPanel);
otherPanel.add(BorderLayout.CENTER, todoPanel);
otherPanel.add(BorderLayout.EAST, checkPanel);

错误是:

Error message: Exception in thread "main" java.lang.NullPointerException
    at java.desktop/java.awt.Container.addImpl(Container.java:1117)
    at java.desktop/java.awt.Container.add(Container.java:460)
    at GUI.setUpGui(GUI.java:57) at manager.main(manager.java:6)

第 57 行附近的代码:

//setting up otherstuff
otherPanel = new JPanel();
otherPanel.add(BorderLayout.WEST, timingsPanel);
otherPanel.add(BorderLayout.CENTER, todoPanel);
otherPanel.add(BorderLayout.EAST, checkPanel);

以下代码最少,它也显示相同的错误

import javax.swing.*;
import java.awt.*;

public class timeclass
{
    JFrame frame;
    JPanel headerPanel;
    JLabel header;
    JPanel otherPanel;
    JPanel timingsPanel;
    JPanel todoPanel;
    JPanel checkPanel;


    public void setUpGui()
    {
        frame = new JFrame("Time Manager");

        //setting up header
        headerPanel = new JPanel();
        header = new JLabel("Time Manager");
        header.setFont(new Font("Times New Roman", Font.BOLD, 36));
        headerPanel.add(header);

        //setting up otherstuff
        otherPanel = new JPanel();
        otherPanel.add(BorderLayout.WEST, timingsPanel);
        otherPanel.add(BorderLayout.CENTER, todoPanel);
        otherPanel.add(BorderLayout.EAST, checkPanel);

        //setting up frame
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        BoxLayout boxLayout4 = new BoxLayout(frame, BoxLayout.Y_AXIS);
        frame.setLayout(boxLayout4);
        frame.add(headerPanel);
        frame.add(otherPanel);
        frame.setSize(900, 400);
        frame.setVisible(true);
    }
}

标签: javanullpointerexception

解决方案


推荐阅读