Java JPasswordField的困难
我想用JLabel“Password”、JPasswordField和“Login”按钮创建一个简单的窗口。将来我想用数据创建一个数据库,但现在我只想简单地“移动”。如果我在密码字段中写入与字符串字段相等的单词,我想创建新窗口并使旧窗口消失。我的代码:Java JPasswordField的困难,java,Java,我想用JLabel“Password”、JPasswordField和“Login”按钮创建一个简单的窗口。将来我想用数据创建一个数据库,但现在我只想简单地“移动”。如果我在密码字段中写入与字符串字段相等的单词,我想创建新窗口并使旧窗口消失。我的代码: public class Test extends JFrame implements ActionListener { JButton login,exit; JTextField tflogin; JPassword
public class Test extends JFrame implements ActionListener {
JButton login,exit;
JTextField tflogin;
JPasswordField pf;
JLabel lpf,ll;
String llogin = "Marco";
String password = "Result";
JFrame nw;
public Test()
{
setBounds(200, 200, 600, 400);;
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
nw = new JFrame("Frame");
nw.setSize(1200,800);
nw.setVisible(false);
pf = new JPasswordField();
pf.setBounds(200, 150, 150, 20);
add(pf);
tflogin = new JTextField();
tflogin.setBounds(200, 120, 150, 20);
add(tflogin);
lpf = new JLabel("Password");
lpf.setBounds(120, 150, 100, 20);
add(lpf);
ll = new JLabel("Login");
ll.setBounds(120, 120, 100, 20);
add(ll);
login = new JButton("Log");
login.setBounds(180, 180, 100, 20);
add(login);
login.addActionListener(this);
exit = new JButton("Exit");
exit.setBounds(290, 180, 100, 20);
add(exit);
exit.addActionListener(this);
}
public static void main(String[] args)
{
Test MyFrame = new Test();
MyFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == login)
{
if (pf.equals(password));
{
nw.setVisible(true);
}
}
else if (source == exit)
{
dispose();
}
}
}
你的问题之一是:
if (pf.equals(password));
pf是一个
JPasswordField
。使用pf.getText()
并将其与密码进行比较。问题在于将JPasswordField
与字符串进行比较:
pf.equals(password) // pf is of type JPasswordField
尝试getPassword()
返回char[]
:
String pswd = new String(pf.getPassword());
if(pswd.equals(password)) {
nw.setVisible(true);
}
你可以试试这个
public void actionPerformed(ActionEvent e)
{
//Object source = e.getSource();
if( e.getSource() == login)
{
String user_password= pf.getText(); //you can use char [] user_password=pf.getPassword();
if (user_password.equals(password));
{
dispose();
nw.setVisible(true);
}
}
else if (source == exit)
{
dispose();
}
}
所以您遇到了什么问题?对不起,我的语言,主要问题->当我单击“日志”按钮时,程序不检查JPasswordField和字符串“password”之间是否相等,如果相同,程序应启动第二个窗口,如果不相同,则不应执行任何操作。。。在我的代码中,当我单击“日志”时,它总是显示第二个窗口。无论我在JPasswordField中写了什么。避免使用null
layouts,像素完美的布局在现代ui设计中是一种错觉。影响零部件单个尺寸的因素太多,您无法控制。Swing的设计初衷是与布局管理器一起工作,丢弃这些布局管理器将导致无止境的问题,您将花费越来越多的时间来纠正这些问题