I'm working on a login system program on Java.
Every time I write down the user and password and press Login it always goes towards the else statement. I did turn the passwordfield
into a string but it still doesn't work.
Here's the code:
public static void main(String[] args)
{
JFrame frame = new JFrame("Login");
frame.setLayout(new BorderLayout());
frame.add(panelC(), BorderLayout.CENTER);
frame.add(panelN(), BorderLayout.NORTH);
//frame.add(panelW(), BorderLayout.WEST);
//frame.add(panelE(), BorderLayout.EAST);
frame.add(panelS(), BorderLayout.SOUTH);
frame.setVisible(true);
frame.pack();
}
public static JPanel panelC()
{
JPanel panel = new JPanel();
label1 = new JLabel("Username");
label2 = new JLabel("Password");
field1 = new JTextField(10);
pass = new JPasswordField(10);
panel.add(label1);
panel.add(field1);
panel.add(label2);
panel.add(pass);
return panel;
}
public static JPanel panelN()
{
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(0,25));
return panel;
}
public static JPanel panelS()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,5));
button1 = new JButton("Login");
JLabel test = new JLabel();
JLabel test2 = new JLabel();
JLabel test3 = new JLabel();
JLabel test4 = new JLabel();
panel.add(test);
panel.add(test2);
panel.add(test3);
panel.add(test4);
panel.add(button1);
char[] p = pass.getPassword();
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent f)
{
try
{
Scanner scan = new Scanner (new File("Logins.txt"));
String user = scan.nextLine();
String pass = scan.nextLine();
String inPass = new String(p);
String inUser = field1.getText();
while (scan.hasNextLine())
{
if (inUser.equals(user) && inPass.equals(pass))
{
System.out.println("Granted");
break;
}
else
{
user = scan.nextLine();
pass = scan.nextLine();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
return panel;
}
}
You're calling getText()
in code where you create a component, so this is being called before a user has had any chance of entering anything into the text field. Instead this method should only be called from within an appropriate listener, such as an ActionListener that is triggered by the user pressing an accept JButton or by pressing enter in a JTextField.
Solution: fill your inPass and inUser Strings within the ActionListener, not within the creational code.
Other problems: