The code below is for a graphical user interface that has a loginframe that will enable the user to input their credentials. However, when I run the code it does not show an output. Can anyone help?
public void addComponentsToContainer() {
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void addActionEvent() {
loginButton.addActionListener(this);
resetButton.addActionListener(this);
showPassword.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
//Coding Part of LOGIN button
if (e.getSource() == loginButton) {
String userText;
String pwdText;
userText = userTextField.getText();
pwdText = passwordField.getText();
if (userText.equalsIgnoreCase("admin") && pwdText.equalsIgnoreCase("12345")) {
JOptionPane.showMessageDialog( null, "Login Successful" );
Home obj= new Home();
obj.setVisible(true);
// setVisible(false);
} else {
JOptionPane.showMessageDialog ( null, "Invalid Username or Password");
}
}
//Coding Part of RESET button
if (e.getSource() == resetButton) {
userTextField.setText("");
passwordField.setText("");
}
//Coding Part of showPassword JCheckBox
if (e.getSource() == showPassword) {
if (showPassword.isSelected()) {
passwordField.setEchoChar((char) 0);
} else {
passwordField.setEchoChar('*');
}
}
}
}
You're not really showing enough information in this particular case which is why your are asked in comments to supply a Minimal Reproducible Example. Never the less, I'm going to go with the fact that you are utilizing a JPasswordField component.
To start with, for security reasons the JPasswordField#getText() method has been Deprecated as of Java 2 platform v1.2 and replaced with the JPasswordField#getPassword() method which returns a char[] Array of the password entered. Although you may still be able to compile with the getText() method for this component on the Java platform you're working with, you may be experiencing issues with it when actually running the code.
Try using the JPasswordField#getPassword() method instead and see if that makes a difference:
String userText = userTextField.getText();
String pwdText = String.valueOf(passwordField.getPassword());
if (userText.equalsIgnoreCase("admin") && pwdText.equalsIgnoreCase("12345")) {
and it should fly...maybe...who knows without a Minimal Reproducible Example. Are you using a JPasswordField or are you using a JTextField with a DocumentFilter to mask the entered text?
Maybe your code is working and you just can't see the Message Box because you use null as the parent for the JOptionPane:
JOptionPane.showMessageDialog( null, "Login Successful" );
and the message box dialog window is sitting behind your application window. This is rather typical if the application window has the setAlwaysOnTop() property set to boolean true. This can give the impression that the application is hanging. Give the dialog a parent...perhaps try loginButton instead of null.
On a side note:
Consider hashing passwords then compare a hash with a hash. You really shouldn't hard-code or store a password as plain-text.
Related
I am developing a system with Java (using NetBeans) and, to make it more "professional", I've added some cool functions, such as Placeholders (Yes, I know, it's from HTML).
For ALL the JTextFields I have, I've used the following code to generate their placeholders (The name of the JTextField in this example is "tfUser") :
private void tfUserFocusGained(java.awt.event.FocusEvent evt) {
if (tfUser.getText().equals("Your User Name...")) {
tfUser.setText("");
tfUser.setForeground(Color.BLACK);
}
}
private void tfUserFocusLost(java.awt.event.FocusEvent evt) {
if (tfUser.getText().equals("")) {
tfUser.setText("Your User Name...");
tfUser.setForeground(Color.GRAY);
}
}
It's a "focus match":
The Text Field has initially the text "Your User Name...", with a "GRAY" foreground. Every time this text field gains the focus, it verifies its text: if the text.equals("Your User Name..."), its text is set to "" (An empty String) and the Foreground is set to BLACK (default). On the other hand, if the text.equals("Anything else..."), it means that the user has probably inserted the user name, so, do not do anything with this code.
Every time the text field loses the focus, it verifies its text: if the text.equals("") (An empty String again), its text is set back to "Your User Name..." and the Foreground is set to GRAY. And again, if the text.equals("Anything else..."), it means that the user has probably inserted the user name, so, do not do anything with this code.
This code is working perfectly with the JTextFields But, when I do the same with JPasswordFields, I get the following result:
****************
(It should be "Your Password...")
Can anyone help me to add a placeholder to this JPasswordField? Thanks in advance.
What i did for my login code was add a checkbox that "shows password" and in the jframe i added this statement:
//Setting checkbox selected to true so the word "password" is seen when program runs
passCheckBox.setSelected(true);
if(passCheckBox.isSelected())
{
PasswordField.setEchoChar((char)0);
}`
Code for password checkbox:
if(passCheckBox.isSelected())
{
PasswordField.setEchoChar((char)0);
}else{
PasswordField.setEchoChar('*');
}
Code for Password Field Focus Gained:
private void PasswordFieldFocusGained(java.awt.event.FocusEvent evt) {
passCheckBox.setSelected(false);
PasswordField.setEchoChar('*');
String password = String.valueOf(PasswordField.getPassword());
if(password.toLowerCase().equals("password"))
{
PasswordField.setText("");
PasswordField.setForeground(Color.black);
}
}
Code for Password Field focus lost:
private void PasswordFieldFocusLost(java.awt.event.FocusEvent evt) {
String password = String.valueOf(PasswordField.getPassword());
if(password.toLowerCase().equals("password") || password.toLowerCase().equals("") )
{
PasswordField.setText("Password");
PasswordField.setEchoChar((char)0);
PasswordField.setForeground(new Color(153, 153, 153));
}
}
I kinda did half of this on my own and took some bits from videos i hope this helps :>
Here is my method for getting the placeholders
private void getPlaceholders(JTextField text) {
String temp = text.getText();
text.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
text.setText("");
text.setForeground(Color.BLACK);
}
#Override
public void focusLost(FocusEvent e) {
if (text.getText().isEmpty()) {
text.setForeground(Color.GRAY);
text.setText(temp);
}
}
});
}
Here is how i implemented it.
// Password Field
passwordField = new JPasswordField();
passwordField.setBounds(48, 340, 288, 32);
roundedPanel.add(passwordField);
passwordField.setText("Password");
passwordField.setEchoChar((char) 0);
getPlaceholders(passwordField);
what allows you to see placeholders in passwordFields is
passwordField.setEchoChar((char) 0);
you can take it out to use in regular text fields
Heya guys! Nolankr here.
I've got this code that enables my password jField when I place something inside the username jField but when I delete my inputs from the username jField my password jField stays enabled. I wanted it to go back to being disabled though. I'm still a starter so I'm so sorry.
private void usernameKeyTyped(java.awt.event.KeyEvent evt) {
String usern = username.getText();
if(usern != null){
password.setEnabled(true);
}else{
password.setEnabled(false);
}
}
I tried coding an infinite loop to it but it just made my .jar file to stop responding / won't close, so I had to close netbeans itself and restart it . xD
username and password are both jTextfields by the way and password is disabled by default
basically,
if username != null then enable password but if username = null again then disable password again
What you probably want is a document listener that will allow you to detect when the username field is changed and take appropriate action.
I'm writing this answer with the mobile app so it's hard to provide a code sample right now.
Basically you would set up the listener on username to check if username is null or empty and enable/disable the password field based on the result of that check.
EDIT:
I'm back at my computer now, and am able to provide a code sample. See below:
userNameTextBox.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) {
handleTextChange();
}
#Override
public void removeUpdate(DocumentEvent e) {
handleTextChange();
}
#Override
public void changedUpdate(DocumentEvent e) {
//Do nothing here
}
private void handleTextChange(){
if(userNameTextBox.getText() == null ||
userNameTextBox.getText().trim().length() == 0){
passwordBox.setEnabled(false);
}else{
passwordBox.setEnabled(true);
}
}
});
Note that the changedUpdate method does nothing because it is not fired when the document text changes, it is fired when attributes change. See the javadoc for complete details.
I have two classes , one called AdminMenu class where variable VoteCycle is a boolean variable that enables a voter to vote provided that the VoteCycle is enabled and another class called LogInMenu where I would like to utilize it.
I'm doing this for my school project.
The problem I have is that even if I select enable which is meant to change the boolean value to true , I'm still getting the false output.. If you don't understand what I mean, my code below should explain it.
Its very basic programming.
The Class
public class AdminMenu extends javax.swing.JFrame {
public boolean VoteCycle;
The method
private void VoteComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
if(vCycle.getSelectedItem().toString().equalsIgnoreCase("True"))
{
VoteCycle=true;
}
else if(vCycle.getSelectedItem().toString().equalsIgnoreCase("False"))
{
VoteCycle=false;
}
}
This is the class where I would like to use the variable to allow users to log in.
The class is called LogInMenu().
At the start of the class I created an object of the class where the variable was defined in using
AdminMenu AdminMenu=new AdminMenu();
DataValidation validate=new DataValidation();
ConnectDB db=new ConnectDB();
I will just post the relevant code for this class:
private void EnterBtnActionPerformed(java.awt.event.ActionEvent evt) {
if(AdminMenu.VoteCycle)
{
String Voter=voter.getText();
boolean detail = false;
if (validate.Verify(Voter))// Validates Data
{
try
{
detail = db.VoterLogIn(Voter);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
if (detail)
{
new VoterMenu().setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(null, "The Username or Password entered is incorrect");// error message
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Voting is currently disabled", "Error", JOptionPane.ERROR_MESSAGE);
}
Even after selecting the combo box option to enabled, I return to the LogInMenu class
and if i attempt to login I receive the "Voting is currently disabled" error.
I would really appreciate any help offered , Thank you!
P.S : I'm unsure how to use a toggle button and allow its state to be kept when logging into the administrators menu or just how to use the toggle button at all.
So instead i'm using a combox box to set my variables values.
The problem I have is that even if I select enable which is meant to
change the boolean value to true , I'm still getting the false
output..
Because, the elements of your JComboBox vCycle are { "Disabled", "Enabled", " " } whereas, you are checking the selectedItem for true and false. You should compare the selected value of vCycle for Diabled or Enabled instead of true and false.
if(vCycle.getSelectedItem().toString().equalsIgnoreCase("Disabled"))
{
VoteCycle=true;
}
else if(vCycle.getSelectedItem().toString().equalsIgnoreCase("Enabled"))
{
VoteCycle=false;
}
}
Apart from checking for the wrong text value of True and False instead of Enabled and Disabled, your code doesn't handle the case where it's neither.
Change your code to the single line:
VoteCycle = vCycle.getSelectedItem().toString().equalsIgnoreCase("Enabled");
Not only is it less code, and more readable, it caters (one way or another) for the neither case.
I have a Swing GUI where I am restricting the user registration so that the username and the password cannot be the same. I am using JoptionPane for the task with the following code:
public void actionPerformed(ActionEvent e) {
String username = tuser.getText();
String password1 = pass1.getText();
String password2 = pass2.getText();
String workclass = wclass.getText();
Connection conn = null;
try {
if(username.equalsIgnoreCase(password1)) {
JOptionPane.showMessageDialog(null,
"Username and Password Cannot be the same. Click OK to Continue",
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
...
The problem is that I had to use System.exit(0); without it, the next code was getting executed. Even after the JOptionPane poped up, the registration was succeeding. I do not need the system to exit, but I need the user to be kept on the registration page after the validation. What is the best way to do this? Is there other convenient ways of doing this rather than using the JOptionPane?
Replace
System.exit(0);
with
return;
if you do not want the rest of the method to be performed
You need to place your code within endless loop, and break it upon successful result. Something like:
while(true)
{
// get input from user
if(vlaidInput) break;
}
place that next code into else part may be it works
if(username.equalsIgnoreCase(password1))
{
JOptionPane.showMessageDialog(null, "Username and Password Cannot be the same. Click OK to Continue","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
//place that next code
// username and password not equals, then it will execute the code
}
First of all, it is best if the UI and business logic (in this case, validation) are separated. Have them separate sort of suggest a better way of handling interaction on its own. Thus, it makes sense to create a separate class UserValidation with method boolean isValid(). Something like this:
public class UserValidation {
private final String name;
private final String passwd;
private final String passwdRpt;
public UserValidation(final String name, final String passwd, final String passwdRpt) {
this.name = name;
this.passwd = passwd;
this.passwdRpt = passwdRpt;
}
public boolean isValid() {
// do your validation logic and return true if successful, or false otherwise
}
}
Then the action code would look like this:
public void actionPerformed(ActionEvent e) {
if (new UserValidation(tuser.getText(), pass1.getText(), pass2.getText()).isValid()) {
// do everything needed is validation passes, which should include closing of the frame of dialog used for entering credentials.
}
// else update the UI with appropriate error message -- the dialog would not close by itself and would keep prompting user for a valid entry
}
The suggested approach gives you a way to easily unit test the validation logic and use it in different situations. Please also note that if the logic in method isValid() is heavy than it should be executed by a SwingWorker. The invocation of SwingWorker is the responsibility of the action (i.e. UI) logic.
hi i have a full screen program which i dont want people to close unless they have a password i have this code at the moment
public void windowClosing(WindowEvent arg0)
{
System.out.println("HERE");
String inputValue = JOptionPane.showInputDialog("Please input the closeword");
if (inputValue != "closeplz")
{
}
}
in the if statement i want it to stop the method so that the program doesent close. any help would be greatly aprecheated thanks ste
You have to call
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
on (or within) the JFrame instance. Then the frame will not close unless you do it manually, though windowClosing() will still be called. Inside it, you can then conditionally call
System.exit(1);
which will end the application. Be sure to do any necessary cleanup first.
Check out Closing an Applicaton for a simple class to help you with this. You would need to provide the custom close action that prompts the user for the password.
Using your simple example the code would be:
Action ca = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
JFrame frame = (JFrame)e.getSource();
String inputValue = JOptionPane.showInputDialog("Please input the closeword");
if (! inputValue.equals("closeplz"))
{
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
};
CloseListener cl = new CloseListener(ca);