猿问

setContentPane() 和 addActionListener 获取

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);

    }

}

该错误与setContentPanein main 方法有关,然后与actionListener. 我在下面发布了确切的错误。为什么是这样?我使用 IntelliJ IDEA GUI 表单创建器创建了它。


Exception in thread "main" java.lang.NullPointerException  

    at Form1.<init>(Form1.java:12)  

    at Form1.main(Form1.java:22)


小怪兽爱吃肉
浏览 167回答 2
2回答

慕娘9325324

在 Java 中,您不能使用未初始化的变量,否则您将收到 NPE。请参阅以下代码,并请阅读 Java 书籍 :)public class Form1 {&nbsp; &nbsp;private JPanel panel1;&nbsp; &nbsp;private JButton button1;&nbsp; &nbsp;public Form1() {&nbsp; &nbsp; &nbsp; panel1 = new JPanel();&nbsp; &nbsp; &nbsp; button1 = new JButton1("Press Me");&nbsp; &nbsp; &nbsp; panel1.add(button1);&nbsp; &nbsp; &nbsp; &nbsp;button1.addActionListener(new ActionListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Button clicked");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;});&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String args[]){&nbsp; &nbsp; &nbsp; &nbsp;JFrame frame = new JFrame("Form 1");&nbsp; &nbsp; &nbsp; &nbsp;frame.setContentPane(new Form1().panel1);&nbsp; &nbsp; &nbsp; &nbsp;frame.pack();&nbsp; &nbsp; &nbsp; &nbsp;frame.setVisible(true);&nbsp; &nbsp; }}

温温酱

因此,您将遇到两个导致该错误的问题。您创建一个对象(之后JButton,JPanel在这种情况下),你必须初始化它们。有很多不同的方法可以做到这一点,这取决于您要尝试做什么,但解决您的问题最简单的方法是在构造函数中添加以下几行:panel1 = new JPanel();button1 = new JButton();之后您的代码应该可以正常运行。
随时随地看视频慕课网APP

相关分类

Java
我要回答