This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                5年前关闭。
            
        

我创建了一个Java应用程序并得到以下异常:

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?我怎么知道?

最佳答案

添加之前,您需要实例化panel。如果在调用MyPanel()之前使用面板,则panel仍为null,因此NullPointerException

当您在这里时,请看一眼。 http://geosoft.no/development/javastyle.html

Java中的方法名称应以小写字母开头的大小写混合,例如myPanel()代替MyPanel()。对我们大多数人来说,MyPanel()乍一看就像一个构造函数,因为您对它的样式设置不当。

此外,MyPanelTextFieldsButtons都应该是私有方法,因为对于外部类来说,调用它们是不合适的。

10-07 22:41