java - 当变量不为空时获取变量的值

标签 java oop

当密码变量不为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/

相关文章:

java - 如何使用 Facebook4j 申请权限?

java - Selenium Grid 和 RemoteWebDriver

c++ - 基类应该具有属性吗?

c# - 即使宣布公开也无法访问属性(property)

javascript - 自动递增对象id JS构造函数(静态方法和变量)

java - Android 中未处理异常

java - 缓慢移动的物体(视觉)

java - IOI Activity 和 AppCompatActivity

javascript - 将一个对象合并到另一个对象的最佳方法(不覆盖)

oop - 函数式编程与面向对象编程