Java setContentPane()和addActionListener获取NullPointerException

Java setContentPane()和addActionListener获取NullPointerException,java,swing,nullpointerexception,Java,Swing,Nullpointerexception,该错误与main方法中的setContentPane有关,然后与actionListener有关。我已经在下面公布了确切的错误。为什么会这样?我使用IntelliJ IDEA GUI表单创建者创建了它 import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Form1 { private JPanel panel1; pri

该错误与main方法中的
setContentPane
有关,然后与
actionListener
有关。我已经在下面公布了确切的错误。为什么会这样?我使用IntelliJ IDEA GUI表单创建者创建了它

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Form1 {
   private JPanel panel1;
   private JButton button1;


   public Form1() {
       button1.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
             System.out.println("Button clicked");
          }
       });
    }

    public static void main(String args[]){
       JFrame frame = new JFrame("Form 1");
       frame.setContentPane(new Form1().panel1);
       frame.pack();
       frame.setVisible(true);
    }
}
线程“main”java.lang.NullPointerException中的异常 在Form1。(Form1.java:12) 位于Form1.main(Form1.java:22)
在Java中,不能使用未初始化的变量,否则将收到NPE。请参阅以下代码并阅读Java书籍:)


因此,您将遇到两个导致错误的问题。创建对象后(
JButton
JPanel
,在本例中),必须实例化它们。有很多不同的方法可以做到这一点,这取决于您试图做什么,但最简单的解决方法是在构造函数中添加以下行:

public class Form1 {
   private JPanel panel1;
   private JButton button1;


   public Form1() {
      panel1 = new JPanel();
      button1 = new JButton1("Press Me");
      panel1.add(button1);
       button1.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
             System.out.println("Button clicked");
          }
       });
    }

    public static void main(String args[]){
       JFrame frame = new JFrame("Form 1");
       frame.setContentPane(new Form1().panel1);
       frame.pack();
       frame.setVisible(true);
    }
}

在此之后,您的代码应该可以正常运行。

您没有初始化panel1。我猜您想创建一个panel1并将button1(也未初始化)添加到其中。请参阅&
public class Form1 {
   private JPanel panel1;
   private JButton button1;


   public Form1() {
      panel1 = new JPanel();
      button1 = new JButton1("Press Me");
      panel1.add(button1);
       button1.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
             System.out.println("Button clicked");
          }
       });
    }

    public static void main(String args[]){
       JFrame frame = new JFrame("Form 1");
       frame.setContentPane(new Form1().panel1);
       frame.pack();
       frame.setVisible(true);
    }
}
panel1 = new JPanel();
button1 = new JButton();