我有一个名为Windows的课程。该类扩展了JFrame并将GUI组件添加到JFrame容器中。其中一个组件是JTextfield。我想在单击生成器JButton时通过actionPerformed()设置JTextfield中的文本。 actionPerformed()是一个名为EvenHandler的类。这是eventHandler:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class EventHandler implements ActionListener {
int x = 0;
PassWordGenerator password;
Window Window; // It works only when static Window Window.
public void start() {
Window = new Window();
}
@Override
public void actionPerformed(ActionEvent e) {
password = new PassWordGenerator(3,3,3,3);
Window.setGeneratedPswd(password.getPswd());
x += 1;
System.out.println(x);
}
public static void main(String[] args) {
EventHandler x = new EventHandler();
x.start();
}
}
窗口类,如果你想知道GUI的样子。该按钮是调用actionePerfome()的按钮。
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
Label passwordLength;
Label labelGnPswd;
JTextField psdLength;
JCheckBox upperCase_letters;
JCheckBox lowerCase_letters;
JCheckBox numbers;
JCheckBox symbols;
JTextField generatedPswd;
EventHandler event = new EventHandler();
JButton generetor;
public Window() {
setLayout(new FlowLayout());
setTitle("PasswordGenerator");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
//Password Length
passwordLength = new Label("Password Length");
add(passwordLength);
//Input text
psdLength = new JTextField("0", 5);
add(psdLength);
//Create checkBoxes
createcheckbxs();
//Label Generated psw
labelGnPswd = new Label("Generated pswd");
add(labelGnPswd);
//Generated Password;
generatedPswd = new JTextField("****", 5);
generatedPswd.setEditable(false);
add(generatedPswd);
//Button
generetor = new JButton("Generate pswd!");
generetor.addActionListener(event);
add(generetor);
setSize(200, 400);
setVisible(true);
}
public String getpsdLength() {
return psdLength.getText();
}
public void setGeneratedPswd(String pswd) {
generatedPswd.setText(pswd);
}
private void createcheckbxs() {
upperCase_letters = new JCheckBox("Include uppercase");
add(upperCase_letters);
lowerCase_letters = new JCheckBox("Include lowercase");
add(lowerCase_letters);
numbers = new JCheckBox("Include numbers ");
add(numbers);
symbols = new JCheckBox("Include symbols ");
add(symbols);
}
}
我的问题是,当我点击生成器JButton时,我会收到一条错误消息,"线程中的异常" AWT-EventQueue-0"显示java.lang.NullPointerException ..."我调试了actionPerformed(),我发现在点击genetor Jbutton后调用actionPefromed()时,Window Window为null。为什么Window为null? Int x工作正常,它不是null。不是var x和window是相同的可变范围。我可以保持Window的值不为null的唯一方法是使Window成为一个静态变量。我希望我的问题更清楚一些。提前致谢
答案 0 :(得分:0)
您的问题似乎在Window.java
:
generetor.addActionListener(event);
变量event
在Window.java
中声明:
EventHandler event = new EventHandler();
问题在于event
start()
未调用,因此其实例变量Window Window
仍为null
。您未在EventHandler
中实例化main()
。你可能会做的是删除你的start
方法并将其内容放在构造函数中。