I have a small issue with my updateButtonResults button. I have JOptionPane Message Dialogs that are programmed to pop up when the user updates the four fields First Name, Last Name, E-mail and Sign-up date. My problem is all 4 messages pop up, even if I only update one field. Example: I update a customers last name, the message dialogs will pop up in this order (First name, Last name, E-mail, Sign-up date).
Here is my code
//method for buttons on 'resultFrame'
public void BtnAction3()
{
updateButtonResults.addActionListener(
new ActionListener()
{
//method for events that will be performed when updateButton is pressed
public void actionPerformed(ActionEvent e)
{
//instanciates variables to text in textfields
String fname = fNameTextBoxResults.getText();
String lname = lNameTextBoxResults.getText();
String email = eMailTextBoxResults.getText();
String signUpDate = signUpTextBoxResults.getText();
try
{
//statement that checks to make sure user enters only letters
if(fname.matches("[a-zA-Z]+"))
{
//updates 'Fname' field in db to text that user inputted in 'fname' textfield
rs2.updateString("Fname", fname);
JOptionPane.showMessageDialog(null, "Customer first name been updated!");
}
//statement that prompts user if they enter something other letters
else
{
JOptionPane.showMessageDialog(null, "Please enter first name in correct format!");
fNameTextBoxResults.setText("");
}
//statement that checks to make sure user enters only letters
if(lname.matches("[a-zA-Z]+"))
{
//updates 'Lname' field in db to text that user inputted in 'lname' textfield
rs2.updateString("Lname", lname);
JOptionPane.showMessageDialog(null, "Customer last name been updated!");
}
//statement that prompts user if they enter something other letters
else
{
JOptionPane.showMessageDialog(null, "Please enter last name in correct format!");
lNameTextBoxResults.setText("");
}
//statement and actions if user enters a '.'
if(email.contains("."))
{
//gets last period in "email"
int emailDotCheck = email.lastIndexOf(".");
//substring to period in variable "emailDotCheck"
String extensionCheck = email.substring(emailDotCheck);
//statement and actions if user doesn't enter email correctly
if(!email.contains("#") || !extensionCheck.matches("\\.[a-z]{3}"))
{
JOptionPane.showMessageDialog(null, "Please enter email in correct format!");
eMailTextBoxResults.setText("");
}
//statement and actions if user enters email correctly
else
{
//updates 'E-mail' field in db to text that user inputted in 'email' textfield
rs2.updateString("E_mail", email);
JOptionPane.showMessageDialog(null, "Customer E-mail been updated!");
}
}
//action if user doesnt enter email correctly
else
{
JOptionPane.showMessageDialog(null, "Please enter email in correct format!");
eMailTextBoxResults.setText("");
}
//instance variables for 'signUpDate'
int month = 100;
int day = 100;
int year = 10000;
if(signUpDate.matches("\\d{2}/\\d{2}/\\d{4}"))
{
//instance variables
String monthStr = signUpDate.substring(0,2);
String dayStr = signUpDate.substring(3,5);
String yearStr = signUpDate.substring(6);
//parsing intstance variables to Integers
month = Integer.parseInt(monthStr);
day = Integer.parseInt(dayStr);
year = Integer.parseInt(yearStr);
//statement and actions if user doesn't follow correct format
if(month > 12 || day > 31 || year > 2100)
{
JOptionPane.showMessageDialog(null, "Please enter date in correct format! (dd/MM/yyyy)");
signUpTextBoxResults.setText("");
}
//statements and actions if user enters date correctly
else
{
//updates 'Sign-up date' field in db to text that user inputted in 'signUpDate' textfield
rs2.updateString("Sign_up_date", signUpDate);
JOptionPane.showMessageDialog(null, "Customer Sign-up date been updated!");
}
}
//statement and actions if user doesn't follow correct format
else
{
JOptionPane.showMessageDialog(null, "Please enter date in correct format! (dd/MM/yyyy)");
signUpTextBoxResults.setText("");
}
//updates row in db
rs2.updateRow();
//JOptionPane.showMessageDialog(null, "Customer has been updated!");
}
catch(Exception ex)
{
}
}
});
I'm trying to learn to walk through my code, I have debugged it, but still couldn't figure the logic error out.
Thanks for any help
You have four text fields:
fNameTextBoxResults
lNameTextBoxResults
eMailTextBoxResults
signUpTextBoxResults
Rather than attempting to validate all of the input at once, let's try to make this code a little more modular. Separate all of the logic pertaining to a specific field and add it as an ActionListener to that field. Example:
fNameTextBoxResults.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//statement that checks to make sure user enters only letters
if(fname.matches("[a-zA-Z]+"))
{
//updates 'Fname' field in db to text that user inputted in 'fname' textfield
rs2.updateString("Fname", fname);
JOptionPane.showMessageDialog(null, "Customer first name been updated!");
}
//statement that prompts user if they enter something other letters
else
{
JOptionPane.showMessageDialog(null, "Please enter first name in correct format!");
fNameTextBoxResults.setText("");
}
}
});
Rinse and repeat for the other three fields. If you have some finalizing type of action required, then you can do that with updateButtonResults. Otherwise, the button is unnecessary altogether.
Instead of using an anonymous class that extends ActionListener, you might want to define a named class that extends it, and defines a constructor by which you could pass in data such as the previous values of the text fields:
class MyActionListener extends ActionListener { // lousy name, but ...
public MyActionListener(String prevFirstName, String prevLastName, String prevEMail, String prevSignUp) {
this.prevFirstName = prevFirstName; ... and so on
}
public void ActionPerformed(ActionEvent e) {
... what you already have, except that you can say things like
if (!fname.equals(prevFirstName)) {
... now you can do your dialog and it won't show up unless the names
... are different
}
...
}
}
and then set it like this:
public void BtnAction3()
{
updateButtonResults.addActionListener(
new MyActionListener(firstName, lastName, eMail, signUp));
}
Related
so I know that there are many similar questions to mine but i do not really understand what they mean as i am not that great when it comes to coding.
my login screen in the GUI is this:
public void createLoginPanel()
{
loginPanel.setLayout(null);
loginLbl.setLocation(425,50);
loginLbl.setSize(500,50);
loginLbl.setText("Login");
loginPanel.add(loginLbl);
usernameLbl.setLocation(250,300);
usernameLbl.setSize(250,50);
usernameLbl.setText("Username: ");
loginPanel.add(usernameLbl);
usernameTxt.setLocation(350,300);
usernameTxt.setSize(250,50);
usernameTxt.setText("");
usernameTxt.setColumns(10);
loginPanel.add(usernameTxt);
passwordLbl.setLocation(250,400);
passwordLbl.setSize(250,50);
passwordLbl.setText("Password: ");
loginPanel.add(passwordLbl);
passwordTxt.setLocation(350,400);
passwordTxt.setSize(250,50);
passwordTxt.setText("");
passwordTxt.setColumns(10);
loginPanel.add(passwordTxt);
loginBtn.setLocation(675,400);
loginBtn.setSize(100,50);
loginBtn.addActionListener(this);
loginBtn.setText("Login");
loginPanel.add(loginBtn);
gotoWelcomeScreenBtn2.setLocation(100,600);
gotoWelcomeScreenBtn2.setSize(150,50);
gotoWelcomeScreenBtn2.addActionListener(this);
gotoWelcomeScreenBtn2.setText("Home");
loginPanel.add(gotoWelcomeScreenBtn2);
}
the login i currently have is this:
if(e.getSource() == loginBtn)
{
String pass;
String user;
user = usernameTxt.getText();
pass = passwordTxt.getText();
if(user.equals("username") && pass.equals("pass") )
{
JOptionPane.showMessageDialog(null,"Login successful");
allTheGUITabs.setSelectedIndex(7);
}
else
{
JOptionPane.showMessageDialog(null,"Please try again.");
}
System.out.println("Login Button pressed");
}
i want to login using existing info that i have stored in a text file called "employeelist.txt" and i am not sure how to do this.
edit: i have changed the login to user.equals and pass.equals but i am still unsure on how to login with anything other than what i've declared.
edit:
this is the contents of my text file. the second is the username and the third is the password. how will i scan this text file to ensure that the username and password match?
1,MSmith01,Pass123,Mark Smith,12 Yellow Lane,L34GF4,07837463
2,JSmith02,Pass456,Joan Smith,8 Green Road,L394RQ,08765456765
3,PSmith03,Pass678,Paul Smith,9 Orange Street,L435RE,07485747362
4,WSmith04,Pass910,Walter Smith,8 Green Road,L394RQ,08765456765
5,CSmith05,Pass149,Callum Smith,12 Yellow Lane,L34GF4,07485848373
6,MSmith06,Pass213,Mark Smith,32 Red Road,L384GT,07874636472
7,TMath07,Pass141,Terry Matthews,4 Peach Street,L219RB,07564737283
Let’s say you have next strings in your txt file
admin
qwerty12345
Use scanner and pass values for your variables reading them from txt
File employeelist;
Scanner scanner;
String login;
String password;
try
{
employeelist = new File("employeelist.txt"); // changed code
scanner = new Scanner(employeelist); //changed code
while(scanner.hasNextLine())
{
login = scanner.nextLine();
password = scanner.nextLine();
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
}
Then use it in your if statement.
if(user.equals(login) && pass.equals(password)
{
// your code here
}
Hello everyone at StackOverflow,
I will be asking a question that I'm confused about and searched for hours for, it's to put a 2-Step authentication on a Java program, what I want is that is send a generated code to a login page like the one I created below.
package log;
import javax.swing.JOptionPane;
public class Login {
public static void main(String args[]) {
String username = JOptionPane.showInputDialog("Enter your username");
String password = JOptionPane.showInputDialog("Enter your password");
if (
username != null && password != null &&
(
(username.equals("g17") && password.equals("ire35")) ||
(username.equals("ree") && password.equals("melikejava")) ||
(username.equals("citizenzap") && password.equals("javarules23"))||
(username.equals("devs") && password.equals("password"))
)
)
{
JOptionPane.showMessageDialog(null, "Logged in!" );
} else {
JOptionPane.showMessageDialog(null, "Incorrect username or password! Try again later." );
}
}
}
Everything is fine with the code above, it's just that I want to send a randomly generated code to a phone number, like as I said before a 2-Step verification. Like Google has or Microsoft and etc. For example: You write a phone number, 123-456-7890, then it sends a code to the phone number and it's says something like Your code is 178634 then you write it into the input box, then it checks if it was the code it sent.
If the question I said is not specific enough or something like that please tell me.
Thanks and keep on coding!
-CitizenZap
First, I suggest you put your data in map, combine username, password, phoneNumber into one class, like UserInfo. Because you need to bind phoneNumber to user, or any phoneNumber after login is acceptable.
Then, you replace
{
JOptionPane.showMessageDialog(null, "Logged in!" );
}
with
String newPhoneNumber = null;
{
newPhoneNumber = JOptionPane.showInputDialog("Enter your phone number");
}
You need to check if newPhoneNumber equals with the phoneNumber bind to the user.
// this should be in a while(true) loop
if (newPhoneNumber.equals(phoneNumber)) {
sendSms(phoneNumber);
String code = JOptionPane.showInputDialog("Enter your code");
boolean result = validateAuthorizationCode(code); // here you validate the code
if (result) {
JOptionPane.showMessageDialog(null, "Logged in!" );
} else {
JOptionPane.showMessageDialog(null, "Wrong code!" );
}
} else {
noticeWrongNumber(newPhoneNumber); // tell him the number is wrong, please reinput.
}
I'm making a cash register with an "other" option, which allows the user to add an amount through user input. I have done this with a JOptionPane, the "other" button code is the following:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt) {
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try {
double overigePrijs = Double.parseDouble(prijs);
if (overigePrijs > 0){
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
}
catch (Exception letter){
while (true){
prijs = JOptionPane.showInputDialog(this, "Vul a.u.b. alleen cijfers in.");
}
}
This while-loop will not close the JOptionPane, even when inputting numbers, how do I loop this correctly?
Edit after almost finishing my SE studies:
I was missing an if-statement in my while-loop. What I was trying to do was checking if the input of prijs were only numbers and if not, keep showing the dialog. I never got around to fixing this because it's an old project but I should have stated the motivation behind the code more clearly!
The question is not clear itself. What I assume that if the try part does not run as you wish, the JOptionPane should reopen and user should be prompted to do it again. If it is so, you can do the following:
Create a method:
private void doTheTask(){
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try{
//your task here.
}
catch (Exception letter){
//Call the method again.
doTheTask();
}
}
And call the method inside your action:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt){
doTheTask();
}
I suggest you a different approach in your code:
String prijs = "";
double overigePrijs = -1;
while (true) {
prijs = JOptionPane.showInputDialog(null, "Vul een bedrag in");
if (prijs != null) { // if user cancel the return will be null
try {
overigePrijs = Double.parseDouble(prijs);
break; // Exits the loop because you have a valid number
} catch (NumberFormatException ex) {
// Do nothing
}
} else {
// You can cancel here
}
// You can send a message to the user here about the invalid input
}
if (overigePrijs > 0) {
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
This code will loop until the user enters a valid number and then you can use after the while loop. Some improvement may be necessary like a cancel logic or change the message on the second time but the main idea is this.
I'm doing input validation on a program using JOptionPane boxes. I'm trying to have the input box repeat after the error message every time the user enters in a non-double. How would I do this?
try {
lengthResult = Double.parseDouble(JOptionPane.showInputDialog("What is the length of your garage in square feet?"));
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please enter a number in digit format.","Inane error",JOptionPane.ERROR_MESSAGE);
}
If you want to repeat the message box until the user enters something valid, I'd go like this:
Double lengthResult = null; //Init to null, which is invalid
String title = "Please anter a number";
int initialType = JOptionPane.QUESTION_MESSAGE;
do {
try {
lengthResult = Double.parseDouble(
JOptionPane.showInputDialog(null,
"What is the length of your garage in square feet?",
title, initialType));
} catch (NumberFormatException e) {
initialType = JOptionPane.ERROR_MESSAGE;
title = "Error: Please enter a number!";
}
} while(lengthResult == null); //Iterate as long as no valid input found
Note that this check relies on lengthResult being an Object of type Double, not a primitive type double. With primitive double you'd need some extra flag as you cannot check on lengthResult value this way.
Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.