在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 */
}
建议一些想法。
答案 0 :(得分:1)
我嘲笑了你的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,它会声明如果NullPointerException
为null,则此方法会抛出comp
。检查您要添加到其中的所有组件,然后您可以弄清楚其余部分。