[英]Java JPasswordField .getPassword() issues
我正在使用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);
}
在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();
}
或可能是因为您在字符串和字段中使用了相同的名称
您的代码中有一些错误。 首先,在父面板中两次添加“用户” 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个字符,则由于大小限制,我将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.