本文介绍了什么是Java NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Java应用程序并获得此异常:

I created a Java Application and get this Exception:

Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at javax.swing.JFrame.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at Executer.<init>(Executer.java:21)
    at Executer.main(Executer.java:14

以下是代码:

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

public class Executer {

private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious;
private JPanel panel;

public static void main(String[] args) {
    new Executer();
}
public Executer() {
    JFrame frame = new JFrame("Execute Script");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(900,400);
    frame.setVisible(true);
    frame.add(panel);
    frame.setVisible(true);
    MyPanel();
    Text();
    Buttons();
    Fields();
}
public void MyPanel() {
    panel = new JPanel();
    panel.setLayout(null);
}
public void Text(){
    lblCommand = new JLabel("Enter Here");
    lblCommand.setBounds(135, 50, 150, 20);
    Font styleOne = new Font("Arial", Font.BOLD, 13);
    lblCommand.setFont(styleOne);
    panel.add(lblCommand);
}

public void Fields () {
    txtEnter = new JTextField();
    txtEnter.setBounds(210, 50, 150, 20);
    panel.add(txtEnter);
}
public void Buttons() {
    btNext = new JButton ("Next");
    btNext.setBounds(380,325,100,20);
    panel.add(btNext);

    btPrevious = new JButton ("Previous");
    btPrevious.setBounds(260,325,100,20);
    panel.add(btPrevious);
}}

什么是NullPointerException?我怎么知道?

What is a NullPointerException? How would I find out?

推荐答案

你需要在实例化面板之前添加它。如果在调用 MyPanel()之前使用面板,面板仍然是 null ,因此 NullPointerException

You need to instantiate panel before adding it. If you use panel before calling MyPanel(), panel is still null, hence the NullPointerException.

当你在这里时,请先看一眼。

While you're here, give this a glance. http://geosoft.no/development/javastyle.html

Java中的方法名称应该是以小写字母开头的混合大小写,例如 myPanel()而不是 MyPanel()。对于我们大多数人来说, MyPanel()乍一看看起来像构造函数,因为你的样式不正确。

Method names in Java should be mixed case starting with a lower case letter, e.g. myPanel() instead of MyPanel(). To most of us, MyPanel() looks like a constructor at first glance because you improperly styled it.

另外, MyPanel 文本字段按钮应该都是私有方法,因为外部类调用它们是不合适的。

Additionally, MyPanel, Text, Fields, and Buttons should all be private methods, as it would be improper for an external class to call them.

这篇关于什么是Java NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 16:57