0

New to java and new to GUI, so my code might not be perfect, but I'm trying to get the user to input a password. If it's correct, I want to return value 1 to main, and if it isn't, then a value 0 to main.

But this part of the code, although it WORKS, the frame automatically disappears and the control goes back to main returning default value of accessFlag = 0, and the program continues from there.

I want it to wait for user input, instead of appearing and vanishing.

public int access(){

    JFrame frame=new JFrame("LOGIN");


    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setSize(510,100);
    JPanel panel=new JPanel(new MigLayout("", "[][][]", "[]"));
    frame.add(panel);
    JButton button=new JButton("Enter");
    JLabel label=new JLabel("Enter Password");
    JPasswordField pass=new JPasswordField(10);
    pass.setEchoChar('*');
    panel.add(label,"cell 0 0 1 1");
    panel.add(pass,"cell 1 0 1 1");
    panel.add(button,"cell 2 0 1 1");
    frame.setVisible(true);

    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            JPasswordField input=(JPasswordField) e.getSource();
            char[] passwordArray= input.getPassword();
            String passwordString= new String(passwordArray);

            if(passwordString.equals(password)){
                JOptionPane.showMessageDialog(null, "Correct!");
                accessFlag=1;
            }
            else{
                String notAllowed="Incorrect";
                JOptionPane.showMessageDialog(null, notAllowed);
                accessFlag=0;
            }
        }
    });

    return accessFlag;
}
ItamarG3
  • 4,092
  • 6
  • 31
  • 44
Minhaj Ansari
  • 81
  • 1
  • 4

0 Answers0