开发者

How to wait till one of the buttons is clicked?

I am working on a project and have stuck at a point. I am working with Java Swing and this is the Problem:

When the user clicks on readMore button, I am creating an instance of class VerifyFF. Now, this class creates a frame which has an input field and two buttons namely cancel and continue. If the user presses cancel, then the frame disposes and nothing needs to be done. If he enters the correct password in the text field and then presses cont, I need to check whether the password is correct or not. For this I am using a boolean variable named as verified.

When the password entered is correct then the value of verified is set to true else nothing happens. The user gets and prompt of wrong password and again he can enter the correct password or can press cancel.

Now, in the class where I am creating the instance of VerifyFF class, I want to check whether the entered password was correct or not, hence开发者_运维问答 I am checking for the value of variable boolean (which is also static). The trouble is, when the constructor of VerifyFF runs, there is nothing which stops the execution and waits for the user to enter something. Both the checking is done inside the function

JButton.addActionListener(new ActionListener()
{
};

The code in class instantiating the variable is:

VerifyFF vff = new VerifyFF();

if(vff.verified)

readMore();

Whenever I run this code, it doesn't waits to see whether any button is placed or not. I want to know how I can make it to wait till some button is pressed.


You don't have to wait until somebody pressed the button. Just move your

if(vvf.verified) readMode(); 

into your action listener for 'continue' button.


I am not sure of the problem. But maybe you should reconsider your implementation. In the constructor do just the first display then have a function that provides more whenever user clicks on more and password was correct. You really do not need to stop constructor from being constructed, this sounds bad.

Good luck, Boro.


Your class should have a validatePassword method, which could be called on the click of the continue button.

class VerifyFF implements ActionListener {

private static final String ACTION_CONTINUE = "CONTINUE";

private JButton continueBtn = null;
private static boolean valid = false;

public VerifyFF() {
    this.continueBtn = new JButton("Continue");
    this.continueBtn.setActionCommand(VerifyFF.ACTION_CONTINUE);
    this.continueBtn.addActionListener(this);
}

public static boolean validatePassword() {
    //Validates the password field...
}

void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals(VerifyFF.ACTION_CONTINUE)) {
        VerifyFF.valid = VerifyFF.validatePassword();
    }
}

}

This way, the validate method is called on the press of the Continue button. and you can then do whatever you need according to the boolean 'valid'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜