我想做一个简单的窗口与JLabel的‘密码’,和JPasswordField,以及“登录”按钮。将来我想用数据做一个数据库,但现在我只想做一个简单的“移动”。如果我在Password Field word中输入等于我的字符串Field,我想创建新窗口并使旧窗口消失。我的代码:
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();
}
}
}发布于 2015-09-23 12:54:56
你的其中一个问题就是:
if (pf.equals(password));pf是一个JPasswordField。使用pf.getText()并将其与口令进行比较。
发布于 2015-09-23 12:58:46
问题是您将JPasswordField与String进行比较
pf.equals(password) // pf is of type JPasswordField尝试返回char[]的getPassword()
String pswd = new String(pf.getPassword());
if(pswd.equals(password)) {
nw.setVisible(true);
}发布于 2015-09-23 13:02:37
你可以试试这个
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();
}
}https://stackoverflow.com/questions/32724418
复制相似问题