我正在使用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);
}发布于 2016-07-13 19:24:19
在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-13 19:31:09
你的代码中有一些错误。首先,在父面板中添加两次'user‘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个字符,我将不会工作,因为你已经限制了大小。
https://stackoverflow.com/questions/38350004
复制相似问题