当密码变量不为null
时,我需要从主类中的PasswordFrame获取密码变量的值。这是PasswordFrame的代码:
public class PasswordFrame extends JFrame {
static JTextField tf;
static JButton button;
public String password;
boolean isPassword = false;
public PasswordFrame(){
tf = new JTextField();
button = new JButton("Enter");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
password = tf.getText();
isPassword = true;
}
});
}
我已经尝试过使用以下代码来做到这一点:
public String getPassword(){
while(!(isPassword)){
}
System.out.println("out");
return password;
}
但是当我尝试
PasswordFrame passwordfield = new PasswordFrame();
if (password.equals(passwordfield.getPassword())){
//code
}
“out”不会被打印,并且无法退出 while
循环。为什么?以及如何使PasswordFrame正常工作并返回密码。
附注如果您打算投反对票,请告诉我可以改进哪些方面以使我的问题更加清晰。
最佳答案
试试这个:
public class PasswordFrame extends JFrame {
static JTextField tf;
static JButton button;
public String password;
boolean isPassword = false;
public PasswordFrame(){
tf = new JTextField();
button = new JButton("Enter");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
password = tf.getText();
/*
* Check for non-null password must check both
* conditions ion this order
*/
if(if(password != null && ! password.isEmpty()){
isPassword = true;
}
}
});
}
关于java - 当变量不为空时获取变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901283/