Creating a Log-In Screen with Validation? - java

I'm creating a Java log-in screen for a scheduling program that uses one-way encryption. The program should work as follows:
If it's the first time opening the program, ever, a window will show up asking the user to enter a username and password, as well as a security question. This first time, the password will not be hidden by black circles. Instead, it will be shown in plain text.
Then, the three fields will be encrypted using a caesar/shift cipher of 3 spots, and the 'encrypted' values will be saved into a file called info.txt in the source folder of the program.
The user will then be redirected to a log-in page, where they will re-enter their username and password to log in. Here, the password field is fixed so that the letters show up as black circles(not sure what this is called). A new int variable called loginAttempts is declared and initialized with the value 0.
After the user hits 'log-in', the system will use the same encryption method for the log-in details entered and compare them to the encrypted information in the text file. If both values match, then the user will be re-directed to the main screen of the program, having been granted access.
If not, then loginAttempts increments. After the 5th time, this happens, the user will be asked their security question. If the answer this wrong the first time, they will be booted from the program.
I have a few questions, as I'm having trouble creating this.
The dialog boxes I'm using to produce error messages are very confusing, and not seeming to work. I got the code to use them straight from the Oracle website and I'm still having trouble-- NetBeans has informed me that it 'cannot find symbol' for showInputDialog(the method I'm using to display the error message), but it's not suggesting that I'm missing any imports.
String errorMessage = "Security Question: What was your favorite class in college?";
String s = (String) JTextField.showInputDialog(
null,
errorMessage,
"ERROR",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.WARNING_MESSAGE,
null,
securityAnswer);
The part that's given me an error is the word 'showInputDialog' itself, and I'm unsure why..? I would like for this particular dialog to appear with a text field in it so that the user can enter the answer to the security question in there. However, the code doesn't even seem to be working.
On the Oracle page, this is the code that is given that is supposed to show a dialog box with an input field:
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
null,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");
But the word frame creates an error in the Netbeans GUI, and I'm not sure why it doesn't work. All I want is to create a text box that looks like this:
but I don't know how to do that in a way that would work.
The way that I've set up my program, I've made multiple jFrame components(different classes), and I've set it up so that if you were to try and access a different frame, the frame you were currently on would turn invisible. For example:
(a user is on the main screen, and they click on a button that says 'Add Appointment.')
addAppointment a = new addAppointment();
a.setVisible(true);
a.setAlwaysOnTop(true);
this.dispose();
And this works for literally all of my program except for the log-in page!
public createUserPass() throws IOException {
String path="\\src\\Schedulemanager\\pkg\\info.txt";
file = new File(path); //creates new File
if (file.exists()) { //make a new file if it's not already existent
logIn loginPage = new logIn();
loginPage.setVisible(true);
loginPage.setAlwaysOnTop(true);
this.dispose();
this.setVisible(false);
} else {
file.createNewFile(); //creates the new file
initComponents();
}
}
This is the 'main' class in the program that will run if the .jar file is clicked. What it's supposed to do is check if the info.txt file exists. If it does, then obviously the user has already set login information, and it should close itself and open an instance of the logIn class, which is the jFrame that handles the log-in functions once the information has been set. However, it doesn't work! It opens the new logIn class, but it doesn't dispose of the original one where you set the information, to begin with.
It's crucial that the original jFrame is hidden so that the user can't just set a new password every single time they run the program! How can I fix this?
Please let me know if I need to clarify anything.

Related

Data transfer between Java Swing forms

I have 5 forms, one of which opens when the other is closed. 2nd member login screen. The last one is the ticket purchase screen. Reservations are made on the ticket purchasing screen. Member information is kept in the database. If the e-mail and password on the login screen match, login with those in the database. I want to access the current user in the last form.
Unfortunately, I did not take action for this from the beginning. Now, if the login is successful, I can take the user's e-mail and forward it to the last form. I can access the member id from this email and add the member information in the final reservation process.
I cannot forward your member email to the last form! That's the problem. I've done a lot of switching between forms, but I can only do this with forms that are opened and closed consecutively. If I create an object with the constructor and type setVisible(true) in the following way, the email is transferred, but the last form opens after the 1st form. If I remove the setVisible method or make false, even if the data is transferred at the last part, I cannot use it because I cannot print it on the label.
private void btnMemberEnterActionPerformed(java.awt.event.ActionEvent evt) {
BiletAl pencere2 = new BiletAl(txtUyeEPosta.getText(),lbl.getText());
pencere2.setVisible(true);}
public class BiletAl extends javax.swing.JFrame {
public BiletAl() {
initComponents();
}
public BiletAl(String gelenEPosta,String lbl) {
initComponents();
System.out.println(gelenEPosta);
lblGelenEposta.setVisible(true);
lblGelenEposta.setText(gelenEPosta);
}
If this happens: the form opening order is broken. but "nil" text, i.e. the entered e-mail is transferred to the label:
private void btnMemberEnterActionPerformed(java.awt.event.ActionEvent evt) {
BiletAl pencere2 = new BiletAl(txtUyeEPosta.getText(),lbl.getText());
}
If the first part changes just like this:Switching between forms is correct, but even if the data coming as constructor parameter with System.out.println is correct, it does not add it to the label when setLabel. The label does not write "nil" in the incoming email.
Then try to use this commands:
1)this.setVisible(true);
2)this.setVisible(false);

What is a good IF statement to use in my Appium code

New to the site and still trying to get the hang of asking questions.
UPDATE
Ok so after making some changes to my code I now have this IF statement in my code, but my problem is if the IF statement is true then it proceeds to that certain page but however won't click on the button. Is my code correct or am I missing some parts?
driver.findElement(By.id(redButton)).click();
driver.findElement(By.id(good)).click();
driver.findElement(By.id(locator)).click();
//IF statement with variable named "viewdets"
//If "View Details & Pay" button pops up click
if (!driver.findElements(By.id(viewdets)).isEmpty()) {
driver.findElement(By.id(viewdets)).click();
//App Closes and Doesn't Click Pay Button
driver.findElement(By.id(pay)).click();
driver.findElement(By.id(conpay)).click();
//If not then continue to stall and check in
} else {
Thread.sleep(7000);
driver.findElement(By.id(stall)).click();
driver.findElement(By.id(two)).click();
driver.findElement(By.id(three)).click();
driver.findElement(By.id(next)).click();
wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id(pay)));
driver.findElement(By.id(pay)).click();
driver.findElement(By.id(conpay)).click();
driver.findElement(By.id(receipt)).click();
You can probably assert that the next expected element is present on the screen or not.
Assuming the previous two clicks("View Details & Pay" button) if were successful would lead you to this screen or else not.
org.junit.Assert.assertFalse(driver.findElements(By.id(good)).isEmpty());
validate that there exists an element with id good in the page you have navigated to. And then perform an action over it as:
driver.findElement(By.id(good)).click();

JOptionPane.showInputDialog does not open dialog box

I was able to use this code successfully until yesterday, but after that JOptionPane.showInputDialog does not launch the dialog box, be it any simple code.
I use 64 bit system and code was working fine.
I have tried reinstalling Java, selenium, eclipse but nothing helped..I seem to have been missing very small thing. it will be great help if anyone can tell what exactly am I missing.
Here is my code (however any simple code is not working)
public static void main(String[] a) throws Exception {
String[] choices = {
"Belk-Make New Config Changes",
"Belk-Bring Back to Original",
"JCP-Make New Config Changes",
"JCP-Bring Back to Original"};
System.out.println(choices);
String input = (String) JOptionPane.showInputDialog(null,
"What do you want to do...",
"SyPi Config Changes",
JOptionPane.QUESTION_MESSAGE,
null, // use default icon
choices, // Array of choices
choices[0]); // Initial choice
}

Using JFileChosser or FileDialog to generate save dialog window

I am working on Jasper Report. I need to ask from a user where to save the generated report. For that, I need to open a "Save As" dialog box. I tried it using JFileChooser and FileDialog.
But, during execution of my code, when execution reaches the point where the code for the Save As dialog box is written, the code remains stuck there. One thing I noticed is that if you run the JFileChooser and FileDialog code for an open dialog box in a separate java class with its own PSVM, it works well.
But when it is invoked by some other function, execution remain stuck there.
Is there any plugin or jar I need to add to use JFileChooser and FileDialog? Or something else I am missing?
I am using eclipse Java EE kepler and Spring MVC.
A FileDialog is easily handled like this:
public String getFileFromDialog(){
FileDialog dialog=new FileDialog(yourFrame,"Save as",FileDialog.SAVE);
dialog.setVisible(true);
//When you call setVisible(true), the method blocks until the user
//chooses a file or cancels the dialog
return dialog.getDirectory()+dialog.getFile();
}
Be aware that, if the user closes the dialog without any file chosen the method will return the rather weird String "nullnull" as both getDirectory() and getFile() return the String "null" (not null but "null"). You probably have to check this to make sure the user has actually chosen a file.
JFrame frame= new JFrame();
frame.setAlwaysOnTop(true);
frame.setVisible(true);
FileDialog fd = new FileDialog(frame, "Save as", FileDialog.SAVE);
fd.setAlwaysOnTop(true);
fd.setVisible(true);
String path=fd.getDirectory().toString()+fd.getFile().toString();
input=cl.getResourceAsStream(total_employee_record);
report=JasperCompileManager.compileReport(input);
parameters.put("mypic",inputimage);
print=JasperFillManager.fillReport(report, parameters,new JRBeanCollectionDataSource(beanlist,false));
JasperExportManager.exportReportToPdfFile(print,path);
}
..........
This is my service method. Now thing that happened is save as dialog box is opened,but in the background. Means everytime I have to minimize eclipse to set the path.
Get me solution please.
My apologies for the bad formating.

How do I change the value of a JOptionPane from a PropertyChangeListener without triggering the listener?

I am trying to make a program to manage a group of sports players. Each player has an enum Sport, and SportManager has convenient factory methods. What I am trying to do is open a dialog that has a JTextField for a name and a combo box to choose a sport. However, I want to stop the user from closing the dialog while the text field is blank, so I wrote a PropertyChangeListener so that when the text field is blank, it would beep to let the user know. However, if the user puts in something in the text after setting off the beep, it doesn't trigger the listener and you can't close the dialog without pressing cancel because the value is already JOptionPane.OK_OPTION, and cancel is the only way to change JOptionPane.VALUE_PROPERTY. So I tried to add
message.setValue(JOptionPane.UNITIALIZED_VALUE);
within the listener. However this just closes the window right away without giving the user a chance to fill in the text field, presumably because it triggers the listener I just registered. How do I make it so that it will beep more than once and give the user a chance to fill in the field?
FYI newPlayer is the component I'm registering the action to.
Code:
newPlayer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object[] msg = new Object [4];
msg[0] = new JLabel("Name:");
final JTextField nameField = new JTextField();
msg[1]=nameField;
msg[2] = new JLabel("Sport: ");
JComboBox<Sport> major = new JComboBox<Sport>(SportManager.getAllSports());
msg[3]=major;
final JOptionPane message = new JOptionPane();
message.setMessage(msg);
message.setMessageType(JOptionPane.PLAIN_MESSAGE);
message.setOptionType(JOptionPane.OK_CANCEL_OPTION);
final JDialog query = new JDialog(gui,"Create a new player",true);
query.setContentPane(message);
query.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
message.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (query.isVisible()&& (e.getSource() == message)&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
if(nameField.getText().equals("")&&message.getValue().equals(JOptionPane.OK_OPTION)){
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
return;
}
query.dispose();
}
}
});
query.pack();
query.setVisible(true);
if(Integer.parseInt(message.getValue().toString())==JOptionPane.OK_OPTION){
players.add(new Player(nameField.getText(),(Sport)major.getSelectedItem()));
edited=true;
}
gui.show(players);
}
});
I don't think you can do it with JOptionPane but you can using using TaskDialog framework and few others.
You can also create a dialog yourself, attach change listeners to your fields and enable/disable OK button based on content of your fields. This process is usually called "form validation"
However, I want to stop the user from closing the dialog while the
text field is blank
I get where you are going, but Java Swing is not very good at this. There is no way you can prevent the listener from being called. A solution would be to ignore the call, but this is complicated to implement.
The way I solved this issue is to let the pop-up disappear, check the returned value and if it is null/empty, beep and re-open it until user fills something.
JOptionPane does not internally support validation of inputs (Bug Reference). Your best bet is to create your own custom JDialog which supports disabling the OK button when the input data is invalid.
I'd recommend reading the bug report since other people talk about it and give workarounds.
However, I want to stop the user from closing the dialog while the text field is blank
The CustomDialog example from the section in the Swing tutorial on Stopping Automatic Dialog Closing has a working example that does this.
After taking a quick look at your code and the working example I think your code should be something like:
if (query.isVisible()
&& (e.getSource() == message)
&& (prop.equals(JOptionPane.VALUE_PROPERTY)))
{
if (message.getValue() == JOptionPane.UNINITIALIZED_VALUE)
return;
if (nameField.getText().equals("")
&& message.getValue().equals(JOptionPane.OK_OPTION))
{
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
else
query.dispose();
}
Otherwise, I'll let you compare your code with the working code to see what the difference is.
One way to solve this problem is to add a Cancel and Ok button to your dialog. Then, disable closing the popup via the X in the corner, forcing the user to click either Cancel or Ok to finish/close the dialog. Now, simply add a listener to the text field that will disable the Ok button if the text field is blank.
Judging from your code I assume you can figure out how to implement these steps, but if you have trouble let us know! Good luck!

Categories

Resources