条件是不检查。 Java, AWT
The condition is not checking. Java, AWT
我正在 Java 使用 AWT 编写一个小型登录表单。在检查用户登录输入时遇到问题:我需要,当用户输入 "admin" 作为登录名和 "password" 作为密码时,程序输出 "Succes!",但无论如何我都会收到 "Wrong!" 消息, 即使输入的数据满足条件。
那么,我应该怎么做才能使程序正确检查条件?
代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Login extends JFrame {
private JButton button = new JButton("Confirm");
private JLabel label1 = new JLabel("Login:");
private JTextField login = new JTextField("", 8);
private JLabel label2 = new JLabel("Password:");
private JTextField pswrd = new JTextField("", 8);
public Login() {
super("Please log in");
this.setBounds(100, 100, 250, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3,2,2,2));
container.add(label1);
container.add(label2);
container.add(login);
container.add(pswrd);
button.addActionListener(new ButtonEvent());
container.add(button);
}
class ButtonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (login.getText() == "admin" && pswrd.getText() == "password")
{
JOptionPane.showMessageDialog(null, "Succes!", "Output", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Wrong!", "Output", JOptionPane.PLAIN_MESSAGE);
}
}
}
public static void main(String[] args) {
Login app = new Login();
app.setVisible(true);
}
}
只需尝试 .equals()
而不是 ==
我正在 Java 使用 AWT 编写一个小型登录表单。在检查用户登录输入时遇到问题:我需要,当用户输入 "admin" 作为登录名和 "password" 作为密码时,程序输出 "Succes!",但无论如何我都会收到 "Wrong!" 消息, 即使输入的数据满足条件。
那么,我应该怎么做才能使程序正确检查条件?
代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Login extends JFrame {
private JButton button = new JButton("Confirm");
private JLabel label1 = new JLabel("Login:");
private JTextField login = new JTextField("", 8);
private JLabel label2 = new JLabel("Password:");
private JTextField pswrd = new JTextField("", 8);
public Login() {
super("Please log in");
this.setBounds(100, 100, 250, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3,2,2,2));
container.add(label1);
container.add(label2);
container.add(login);
container.add(pswrd);
button.addActionListener(new ButtonEvent());
container.add(button);
}
class ButtonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (login.getText() == "admin" && pswrd.getText() == "password")
{
JOptionPane.showMessageDialog(null, "Succes!", "Output", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "Wrong!", "Output", JOptionPane.PLAIN_MESSAGE);
}
}
}
public static void main(String[] args) {
Login app = new Login();
app.setVisible(true);
}
}
只需尝试 .equals()
而不是 ==