gpt4 book ai didi

java - 添加框架内容时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 12:20:20 25 4
gpt4 key购买 nike

在 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 但没有实例化该对象,然后我尝试将其添加到内容 Pane 中。在我的例子中,这导致了 NullPointerException

我的结论:您正在将一个组件添加到尚未正确实例化的容器中。事实上,如果您阅读 Container.add(comp) 方法的 Javadoc,它会指出,如果 comp 为无效的。检查您尝试添加到其中的所有组件,然后您就可以找出其余的组件。

关于java - 添加框架内容时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26709282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com