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.
Related
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.
Not getting sessin value in vaadin framework
Used below :
private void setCurrentUsername(String username){
VaadinService.getCurrentRequest().getWrappedSession().setAttribute("LOGGED_IN_AS_USER",username);
userSubMenu.setText(username);
}
public static String getCurrentUsername() {
//log.info("User:::::::::::::::::" + (String) VaadinService.getCurrentRequest().getWrappedSession().getAttribute("LOGGED_IN_AS_USER"));
return (String) VaadinService.getCurrentRequest().getWrappedSession().getAttribute("LOGGED_IN_AS_USER");
}
getting value as null when flow going to other class
You could try using VaadinSession.getCurrent().getSession() instead?
iIf you are using this for a user interface i.e a user logging in. Don't forget that when your app first builds/ when the user first enters it they will of course have a null value(including any sub pages).
Try adding a ViewChangeListener to the page that the user now enters (apologies for any errors in coding i'm not currently able to gain access to my machine) into:
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
this.username = VaadinSession.getCurrent().getAttribute("LOGGED_IN_AS_USER");
}
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'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.
if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
You need an Alert:
An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.
With 2 commands ("Yes"/"No" in your case):
If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.
These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing CommandListener, and prepare your code for asynchronous execution.
Here is an (untested!) example class based on Alert:
public class MyPrompter implements CommandListener {
private Alert yesNoAlert;
private Command softKey1;
private Command softKey2;
private boolean status;
public MyPrompter() {
yesNoAlert = new Alert("Attention");
yesNoAlert.setString("Are you sure?");
softKey1 = new Command("No", Command.BACK, 1);
softKey2 = new Command("Yes", Command.OK, 1);
yesNoAlert.addCommand(softKey1);
yesNoAlert.addCommand(softKey2);
yesNoAlert.setCommandListener(this);
status = false;
}
public Displayable getDisplayable() {
return yesNoAlert;
}
public boolean getStatus() {
return status;
}
public void commandAction(Command c, Displayable d) {
status = c.getCommandType() == Command.OK;
// maybe do other stuff here. remember this is asynchronous
}
};
To use it (again, untested and on top of my head):
MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());
This code will make the prompt the current displayed form in your app, but it won't block your thread like in the example you posted. You need to continue running and wait for a commandAction invocation.
I dont have programed in Java ME, but i found in it's reference for optional packages the
Advanced Graphics and User Interface API, and it's used like the Java SE API to create these dialogs with the JOptionPane Class
int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)
Return could be
JOptionPane.YES_OPTION, JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION...