0

我正在使用 JPasswordField 来获取登录功能的用户名和密码。.getPassword 适用于密码,但不适用于用户名。如果我输入相同的内容,知道为什么它不适用于用户名吗?

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;

class pros
{
    JFrame frame;
    private static void show(){
    JFrame frame = new JFrame("LOGIN");
    frame.setSize(450,450);
    frame.setLayout(new GridLayout(0,1));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel(); 
    panel.setBackground(Color.BLACK);

    JLabel username = new JLabel("Enter the Username: ",JLabel.LEFT);
    username.setForeground(Color.WHITE);
    username.setFont(username.getFont().deriveFont(24f));
    panel.add(username);

    JPasswordField user = new JPasswordField(10);
    user.setEchoChar('?');
    panel.add(user);

    JLabel password = new JLabel("Enter your Password: ",JLabel.RIGHT);
    password.setForeground(Color.WHITE);
    password.setFont(password.getFont().deriveFont(24f));
    panel.add(user);
    panel.add(password);

    JPasswordField field = new JPasswordField(10);
    field.setEchoChar('•');

    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) 
        {
            String input = String.valueOf(field.getPassword());
            String user = String.valueOf(user.getPassword());
            if(input.equals("double" && user.equals("relocating")))
            {
                field.setText("");
               pane();
        }
    }});
    panel.add(field);
    panel.add(ok);
    frame.add(panel);
    frame.setVisible(true);
}
4

2 回答 2

0

在 if 语句之前使用 System.out.println(input+" "+user) 只是为了查看变量的值是什么,然后您就会知道问题并可以解决它

{
        String input = String.valueOf(field.getPassword());
        String user = String.valueOf(user.getPassword());
        System.out.println(input+"  "+user);//here print see the consul to know why it's not working
        if(input.equals("double" && user.equals("relocating")))
        {
            field.setText("");
           pane();
    }

或者可能是因为您对字符串和字段使用相同的名称

于 2016-07-13T11:24:18.587 回答
0

您的代码中有一些错误。首先,您在父面板中添加了两次“用户”JPasswordField。第一次在这里完成:

JPasswordField user = new JPasswordField(10);
user.setEchoChar('?');
panel.add(user);

初始化组件后,在此处进行一个:

JLabel password = new JLabel("Enter your Password: ",JLabel.RIGHT);
password.setForeground(Color.WHITE);
password.setFont(password.getFont().deriveFont(24f));
panel.add(user);
panel.add(password);

其次,为什么在按钮初始化后将组件添加到面板“字段”(连同它的侦听器)。

第三,你的用户名有多长?如果它超过 10 个字符,我将无法工作,因为您限制了大小。

于 2016-07-13T11:31:09.403 回答