Reputation: 65
i've tried searching Stack Overflow and Code Ranch but with no luck with my query. I'll try and make it as simple and straight forward as possible. What i'm trying to do is have a login page that when it's clicked it checks the username against what i've coded and if it's right have it dispose of that JFrame and go onto another JFrame. Can anyone point me in the right direction?
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (userTextField.equals(userString)){
frame.dispose();
new SecondFrame();
}
}
});
Where button is the JButton, userTextField is the JTextField, userString is the String where the username is stored and SecondFrame being the JFrame I want it to move to when the JButton is selected
EDIT
public SecondFrame() {
centerPiece.setLayout(new net.miginfocom.swing.MigLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 525);
f.setVisible(true);
f.setLocationRelativeTo(null);
If you want more of it let me know
Upvotes: 2
Views: 487
Reputation: 31891
The correct way to do this is using MVC Pattern.
You should create a Service
and put all your business logic,
example, validating username and password in that service. Create
this method in service in some other file
public class UserServiceImpl {
....
public boolean checkUser(String userName, String password) {
User user = userDaoImpl.getUser(userName);
if(user == null)
return false;
else if (!user.getPassword().equals(password))
return false;
else
return true;
}
....
}
In your view, i.e., your JFrame, you should first initialize your service.You can also create a simple Service object if you're new to this concept.
public class SwingContainerDemo extends JFrame {
UserServiceImpl userService = new UserServiceImpl();
....
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (userService.checkUser(jUserNameTf.getText(), jPassword.getText())){
frame.dispose();
new SecondFrame();
} else {
jAlertTF.setText("Invalid Username password combination");
}
}
....
});
Upvotes: 1
Reputation: 2011
You need to replace this
if (userTextField.equals(userString))
with this
if (userTextField.getText().equals(userString))
,
because without calling getText()
method you won't be able to get the string which is written in the JTextField
.
Upvotes: 1
Reputation: 4929
You need to use the userTextField's getText
method as doing userTextField.equals(userString)
is actually comparing the object userTextField
and userString
Check the javadocs for more info: https://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html
Upvotes: 1