【问题标题】:How to fix this AWT-EventQueue-0 exception [duplicate]如何修复此 AWT-EventQueue-0 异常 [重复]
【发布时间】:2019-06-07 19:36:30
【问题描述】:

我用 Java Swing 编写了一个库登录页面并尝试运行它。该页面可以正常运行,但是当我输入任何用户名,选择类型并按登录时,它会引发AWT-EventQueue-0: NullPointerException

Library 类反序列化两个包含用户和书籍信息的文件,并将它们初始化为对象。

User 是 Member 和 Staff 的父类,Book 类代表一本书及其标题、描述、副本。这些类的方法都是正确的。

LoginWindow.java

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

public class LoginWindow {

    private JFrame frmLogIn;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoginWindow window = new LoginWindow();
                    window.frmLogIn.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Initialize the contents of the frame.
     */
    public LoginWindow() {

        frmLogIn = new JFrame();

        JLabel lblName = new JLabel("Name:");
        lblName.setBounds(23, 25, 46, 14);
        frmLogIn.getContentPane().add(lblName);

        JLabel lblType = new JLabel("Type:");
        lblType.setBounds(23, 56, 46, 14);
        frmLogIn.getContentPane().add(lblType);

        JTextField textField = new JTextField();
        textField.setBounds(71, 22, 158, 20);
        frmLogIn.getContentPane().add(textField);
        textField.setColumns(10);

        JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(new String[] {"Staff", "Member"}));
        comboBox.setBounds(71, 53, 158, 20);
        frmLogIn.getContentPane().add(comboBox);

        JButton btnNewButton = new JButton("Login");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                if (!Library.users.containsKey(textField.getText())) {
                    new CreateUserWindow();
                    frmLogIn.dispose();
                }

                else if (!Library.users.get(textField.getText()).getUserType().equals(comboBox.getActionCommand())) {
                    JOptionPane.showMessageDialog(null,
                            "The user name and user type do not match, please try again.",
                            "User information mismatch", JOptionPane.ERROR_MESSAGE);
                }

                else {
                    String type = comboBox.getActionCommand();
                    if (type.equals("Staff")) new StaffWindow((Staff)Library.users.get(textField.getText()));
                    else new MemberWindow((Member)Library.users.get(textField.getText()));
                }
            }
        });
        btnNewButton.setBounds(23, 88, 206, 23);
        frmLogIn.getContentPane().add(btnNewButton);


        frmLogIn.setTitle("Log in");
        frmLogIn.setBounds(100, 100, 268, 185);
        frmLogIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmLogIn.getContentPane().setLayout(null);
        frmLogIn.setVisible(true);
    }
}

库.java

import java.io.*;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class Library implements Serializable{

    public static HashMap<String, User> users;
    public static HashMap<String, Book> books;

    public Library(boolean readFromSerialized) throws IOException, ClassNotFoundException {
        users = new HashMap<>();
        books = new HashMap<>();

        if (readFromSerialized) {
            ObjectInputStream u_in = new ObjectInputStream(new FileInputStream("./Assignment/data/Users.txt"));
            ObjectInputStream b_in = new ObjectInputStream(new FileInputStream("./Assignment/data/Books.txt"));

            users = (HashMap<String, User>) u_in.readObject();
            books = (HashMap<String, Book>) b_in.readObject();

            u_in.close();
            b_in.close();
        }
    }

    public static void serializeToFile() {
        try {
            ObjectOutputStream u_out = new ObjectOutputStream(new FileOutputStream("./Assignment/data/Users.txt"));
            ObjectOutputStream b_out = new ObjectOutputStream(new FileOutputStream("./Assignment/data/Books.txt"));

            u_out.writeObject(Library.users);
            b_out.writeObject(Library.books);

            u_out.close();
            b_out.close();
        } catch (Exception ex) {}
    }
}

错误信息显示以下代码sn-p包含一些错误,该代码是关于用户信息验证的:

if (!Library.users.containsKey(textField.getText())) {
                    new CreateUserWindow();
                    frmLogIn.dispose();
                }

【问题讨论】:

  • 请不要使用浏览器的back button 来编辑您的问题。它破坏了其他人所做的更改
  • 即使这不是同一个问题的数千次重复,您的请求也远不及minimal reproducible example。在写更多问题之前,请先了解如何以及在此处提出什么问题。

标签: java swing user-interface exception awt-eventqueue


【解决方案1】:

您的代码中有几个问题:

  1. 使用setBounds和使用null-layoutsetLayout(null)),即evilfrowned upon,因为这可能会导致烦人的问题,例如this,使用正确的@987654324 @ 以使您的应用程序在所有操作系统和 PLAF 中正确呈现。

  2. 使用public static 成员,这可能会导致您的申请流程不一致。

  3. 现在,您的问题是您创建了一个全局 textfield 变量但从未初始化它(所以它是null

    private JTextField textField;
    

    但是,在您的构造函数中,您创建另一个具有相同名称的构造函数,但它是一个 本地 变量:

    JTextField textField = new JTextField();
    

    当你调用这条线时:

    else if (!Library.users.get(textField.getText()).getUserType().equals(comboBox.getActionCommand())) {
    

    Java 正在使用 global 变量(记住它是 null),而不是 local 变量(已初始化),为了解决这个问题,删除 @ 987654336@ 关于 local 变量的声明:

    JTextField textField = new JTextField();
    

    所以,它变成:

    textField = new JTextField();
    

    这将初始化全局变量,您将能够在 ActionListener 中使用它

【讨论】:

  • 我刚刚修复了范围问题,但仍然引发了同样的异常。
  • 好吧,除非您发布堆栈跟踪和minimal reproducible example 来解决我提出的所有上述建议,否则我想我无法提供更多帮助。我的猜测是它与Library 类中的static users 变量有关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多