gpt4 book ai didi

java - 操作事件后 JTextField 输入的 getText

转载 作者:行者123 更新时间:2023-12-02 05:02:01 25 4
gpt4 key购买 nike

我是 Java 的新手,我不太明白为什么我无法从我创建的 JTextFields 中获取 getText() 。

我希望能够使用已输入的电子邮件和密码创建一个新用户,但我在 JTextFields emailText 和 passwordText 上收到 nullPointerException,大概是因为即使在字段中输入某些内容后它们仍然为 null运行程序后。

此外,我知道这根本不安全,但现在没关系。

谢谢

import javax.swing.*;

import java.util.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;

public class Login {
JFrame frame;
JPanel panel;
JTextField emailText;
JPasswordField passwordText;
ObjectOutputStream out;
ObjectInputStream in ;

public static void main(String[] args) {
new Login().go();
}

public void go() {
frame = new JFrame("Npact Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

BorderLayout layout = new BorderLayout();
JPanel background = new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

Box buttonBox = new Box(BoxLayout.Y_AXIS);
Font bigFont = new Font("sanserif", Font.BOLD, 24);

JLabel instructions = new JLabel("Welcome.");
instructions.setFont(bigFont);
JLabel instructions2 = new JLabel("To begin, enter the email and password");
instructions2.setFont(bigFont);
buttonBox.add(instructions);
buttonBox.add(instructions2);

JLabel emailLabel = new JLabel("Email:");
JTextField emailText = new JTextField(30);
emailText.requestFocus();
buttonBox.add(emailLabel);
buttonBox.add(emailText);

JLabel passwordLabel = new JLabel("Password:");
JPasswordField passwordText = new JPasswordField(30);
passwordText.addActionListener(new MyStartActionListener());
buttonBox.add(passwordLabel);
buttonBox.add(passwordText);

JButton start = new JButton("Get Started!");
start.addActionListener(new MyStartActionListener());
buttonBox.add(start);

frame.getContentPane().add(buttonBox);
frame.setSize(1000, 250);
frame.setVisible(true);
}

public class MyStartActionListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
String name = emailText.getText();
char[] pass = passwordText.getPassword();

User newUser = new User(name, pass);
try {
out.writeObject(newUser);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
package co.npact;

public class User {
private String email;
private char[] password;

public User(String e, char[] p) {
e = email;
p = password;
}

public String getEmail() {
return email;
}

public char[] getPassword() {
return password;
}
}

最佳答案

您定义了两次文本字段。一次作为实例变量,一次作为局部变量。摆脱局部变量。代码应该是:

//JTextField emailText = new JTextField(30);
emailText = new JTextField(30);

关于java - 操作事件后 JTextField 输入的 getText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28180687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com