Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to compare the inputs of a login form (email and password ) to a text file content(the data are separated with a comma)
the text file looks like this :
email#gmail.com,password,name
my code that I have tried looks like this (the jTextField4 is for the email and jPasswordField1 is for the password) :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
boolean d = false;
Scanner read = new Scanner("data.txt");
read.useDelimiter(",");
while(read.nextLine() !=null){
String user = read.next();
String pass = read.next();
read.next();
if(jTextField4.getText().equals(user)&&jPasswordField1.getText().equals(pass)){
d=true;
break;
}
}
if(d)
JOptionPane.showMessageDialog(null, "Welcome");
else {
JOptionPane.showMessageDialog(null, "Incorrect username or password");
}
}
but it keeps giving me errors
You are using Scanner incorrectly.
Read a line from the file.
Split it on the comma. This will give you an array of two elements where the first element is the username and the second element is the password.
Then compare each element with its corresponding text component.
The while loop should look like the following.
boolean d = false;
while (read.hasNextLine()) {
String line = read.nextLine();
String[] parts = line.split(",");
d = jTextField4.getText().equals(parts[0]) && jPasswordField1.getText().equals(parts[1]);
if (d) {
break;
}
}
According to the javadoc for class java.util.Scanner, method nextLine throws NoSuchElementException when there are no more lines to be read. Hence the while loop calls method hasNextLine in order to make sure that there is another line to be read.
Similarly, method next throws NoSuchElementException when there are no more "tokens" to be read.
You are getting the exception because you are not checking for the end of the file. So if the username and password entered by the user (via the GUI) does not exist in the file, the while loop tries to read past the end of the file and that causes NoSuchElementException to be thrown.
EDIT
Here's how I would do it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class PwChecks implements ActionListener, Runnable {
private static final String CHECK = "Check";
private JFrame frame;
private JPasswordField passwordField;
private JTextField textField;
public void actionPerformed(ActionEvent event) {
Path path = Paths.get("logindtl.txt");
try (Stream<String> lines = Files.lines(path)) {
String name = lines.filter(this::checkLine)
.map(line -> line.split(",")[2])
.findFirst()
.orElseThrow();
JOptionPane.showMessageDialog(frame,
"Welcome " + name,
"Login Successful",
JOptionPane.PLAIN_MESSAGE);
}
catch (IOException xIo) {
JOptionPane.showMessageDialog(frame,
xIo,
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
catch (NoSuchElementException xNoSuchElement) {
JOptionPane.showMessageDialog(frame,
"Incorrect username or password",
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
public void run() {
createAndDisplayGui();
}
private boolean checkLine(String line) {
String[] fields = line.split(",");
String eMail = textField.getText();
char[] letters = passwordField.getPassword();
String password = new String(letters);
return eMail.equals(fields[0]) && password.equals(fields[1]);
}
private void createAndDisplayGui() {
frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createLogin(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JButton createButton(String text, int mnemonic) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(this);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(CHECK, KeyEvent.VK_C));
return buttonsPanel;
}
private JPanel createLogin() {
JPanel login = new JPanel(new GridBagLayout());
login.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.insets.top = 5;
JLabel eMailLabel = new JLabel("eMail");
login.add(eMailLabel, gbc);
gbc.gridx = 1;
textField = new JTextField(12);
login.add(textField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JLabel passwordLabel = new JLabel("Password");
login.add(passwordLabel, gbc);
gbc.gridx = 1;
passwordField = new JPasswordField(12);
login.add(passwordField, gbc);
return login;
}
public static void main(String[] args) {
EventQueue.invokeLater(new PwChecks());
}
}
Here is file logindtl.txt
email#gmail.com,password,name
Here is a screen capture of the GUI.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Here is my code and what I want to do is, when the login button is pressed, I would like it to check the password and text fields for the right password(found in the if statement). I need help on what to do to get the input from the text and password fields. When I run the code, it skips right to the else statement and does the code in there, I want it to do the if statement as I have entered the right username and password. I was trying to figure out how to get input from the text fields but I don't know how to. I would appreciate some help, thank you.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class GUI_2 implements ActionListener {
private JLabel PassLabel;
private JFrame frame;
private JButton enterButton;
private JLabel UserLabel;
private JLabel label;
private JPanel panel;
private JFrame Incorrect;
private JTextField password;
private JTextField username;
private String rightPassword;
private String rightUsername;
private String passwordInput;
private String usernameInput;
private JButton UsernameEnter;
private JButton PasswordEnter;
private final static String newline = "\n";
private TextArea textArea;
public GUI_2()
{
PassLabel = new JLabel("Enter Password:");
password = new JPasswordField(11);
UserLabel = new JLabel("Enter Username:");
username = new JTextField(11);
enterButton = new JButton("Login");
label = new JLabel("Access");
UsernameEnter = new JButton("Enter");
PasswordEnter = new JButton("Enter");
frame = new JFrame();
panel = new JPanel();
Incorrect = new JFrame();
enterButton.addActionListener(this);
panel.setBorder(BorderFactory.createEmptyBorder(200,200,60,300));
panel.setLayout(new GridLayout(5, 5));
panel.add(UserLabel);
panel.add(username);
panel.add(PassLabel);
panel.add(password);
panel.add(label);
panel.add(enterButton);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Password Login");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new GUI_2();
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent arg0)
{
if (passwordInput == "password" && usernameInput == "harry")
{
frame.setTitle("Success");
label.setForeground(Color.green);
label.setText("Access granted");
}
else
{
frame.setTitle("Access Denied");
label.setForeground(Color.red);
label.setText("Access Denied");
}
}
}
1: you can get the input password with: password.getText()
2: you should use "equals" compare two string passwordInput.equals("password")
so modify the actionPerformed method like this:
public void actionPerformed(ActionEvent arg0) {
passwordInput = password.getText();
usernameInput = username.getText();
if (passwordInput != null
&& usernameInput != null
&& passwordInput.equals("password")
&& usernameInput.equals("harry")) {
frame.setTitle("Success");
label.setForeground(Color.green);
label.setText("Access granted");
} else {
frame.setTitle("Access Denied");
label.setForeground(Color.red);
label.setText("Access Denied");
}
}
I want to create a JPasswordField where I can see the characters while typing,
I tried passtxt.setEchoChar((char) 0); but it completely change the '*' to text
I don't want this,
I want to view text while typing character by character
( as we see in mobile browsers)
thanks
import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Main {
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField ");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.add(new JLabel("Username"));
p.add(new JTextField(20));
p.add(new JLabel("Password"));
JPasswordField jpassword = new JPasswordField(20);
p.add(jpassword);
Checkbox c=new Checkbox("type password and click");
c.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
jpassword.setEchoChar('*');
} else {
jpassword.setEchoChar((char) 0);
}
}
});
jpassword.setEchoChar((char)0);
p.add(c);
f.add(p);
f.setSize(300, 200);
f.setVisible(true);
}
}
This is an easy solution. Use a JTextField instead of JPasswordField and a String member to store the real password seperately:
private JTextField textField = new JTextField();
private String password = "";
implement a java.awt.event.KeyListener, and overwrite keyReleased like this:
public void keyReleased(KeyEvent e) {
if (Character.isLetter(e.getKeyChar()) ||
Character.isDigit(e.getKeyChar())) { //Add other valid characters as needed
//Get text and last typed character
String text = textField.getText();
char typed = text.charAt(text.length()-1);
//store typed letter separately for later use
password += (text.length() > 0) ? typed : "";
StringBuilder sb = new StringBuilder();
for (int c=0; c<text.length()-1; c++) {
sb.append("*");
}
sb.append(typed);
//set password with asterisks, for authentication use member: password
textField.setText(sb.toString());
}
Add the Listener to the text field and you're done.
This will overwrite all but the last character typed in with a * any time a new letter or digit is typed.
I have a method like so, which is given an array of JButton and returns their text whenever they are pressed:
public static String foo(JButton[] buttons) {
for (JButton i : buttons) {
i.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
return i.getText();
}
});
}
}
But, of course, this code will not compile because I am returning a variable to a null method. So, how would I have i.getText() return its output too the foo() method?
Edit, all of the code:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JCustomFrame {
public static void showMessageFrame(String title, String message,
String[] textOnButtons, ImageIcon icon) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.RELATIVE;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel messageLabel = new JLabel(message);
messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));
panel.add(messageLabel, c);
c.gridy = 1;
c.gridx = 0;
for (int i = 0; i < textOnButtons.length; i++) {
JButton button = new JButton(textOnButtons[i]);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
return ((JButton) arg0.getSource()).getText();
frame.dispose();
}
});
button.setFont(button.getFont().deriveFont(16.0f));
panel.add(button, c);
c.gridx++;
}
if (icon == null) {
frame.setIconImage(new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE));
} else {
frame.setIconImage(icon.getImage());
}
frame.add(panel);
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
public static void main(String[] args) {
JCustomFrame.showMessageFrame("Test Frame",
"Do you really want to do this?", new String[] { "Hell No",
"Sure, Why Not" }, null);
}
}
This statement doesn't make sense:
So, how would I have i.getText() return its output too the foo() method?
The method foo() is no longer running after the ActionListeners have been added to the buttons, and certainly will have ended by the time a user pushes a button, as per the rules of event-driven programming. Instead, though you could have the ActionListeners change the state of a class, any class, and that should suffice. For instance:
class FooClass {
private String text;
public void foo(JButton[] buttons) {
for (JButton i : buttons) {
i.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text = e.getActionCommand();
}
});
}
}
}
If you need greater detail on a viable solution, please tell us more details about your actual program and your specific problem.
Now if you actually needed a method to return the value of the button pressed, you would need to do this via notification mechanisms and a call-back method, but again the details of a solution will depend on the details of the actual problem and code.
Edit
You're trying to emulate a JOptionPane. Your solution is to either use a JOptionPane, adding a JPanel to it, or create your own using a modal JDialog:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JCustomFrame2 {
public static String showMessageFrame(Window owner, String title,
String message, String[] textOnButtons, ImageIcon icon) {
final JDialog dialog = new JDialog(owner);
StringBuilder sb = new StringBuilder();
// make it application modal!
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.RELATIVE;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel messageLabel = new JLabel(message);
messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));
panel.add(messageLabel, c);
c.gridy = 1;
c.gridx = 0;
for (int i = 0; i < textOnButtons.length; i++) {
JButton button = new JButton(textOnButtons[i]);
button.addActionListener(new ButtonListener(sb));
button.setFont(button.getFont().deriveFont(16.0f));
panel.add(button, c);
c.gridx++;
}
if (icon == null) {
dialog.setIconImage(new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE));
} else {
dialog.setIconImage(icon.getImage());
}
dialog.add(panel);
dialog.setTitle(title);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.pack();
dialog.setVisible(true);
return sb.toString();
}
private static class ButtonListener implements ActionListener {
private StringBuilder sb;
public ButtonListener(StringBuilder sb) {
this.sb = sb;
}
#Override
public void actionPerformed(ActionEvent e) {
sb.append(e.getActionCommand());
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
if (win != null) {
win.dispose();
}
}
}
public static String showMessageFrame(String title,
String message, String[] textOnButtons, ImageIcon icon) {
return showMessageFrame(null, title, message, textOnButtons, icon);
}
public static void main(String[] args) {
String result = JCustomFrame2.showMessageFrame("Test Frame",
"Do you really want to do this?", new String[] { "Hell No",
"Sure, Why Not" }, null);
System.out.println(result);
}
}
Why so complicated? whatever foo is supposed to do, it would be a lot easier to simply call another method from inside the ActionListener with the name of the button as argument. Or, if you really want to achieve something like this, make the thread wait for the user to press a button.
public void doSomething(){
JButton[] someButtons = ...;//whereever you create the buttons
System.out.println(foo(someButtons));
}
public static String foo(JButton[] buttons){
final String someString = "";
final Object lock = new Object();
for(JButton b : buttons){
b.addActionListener(e -> {
someString.concat(b.getName());
synchronized(lock){
lock.notifyAll();
}
});
}
synchronized(lock){
try{
lock.wait();
}catch(InterruptedException e){}
}
return someString;
}
I'm trying to make a program which the user signs up and his information gets output to a file using simple text output?
Here is my whole class..
package malkawi.login;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.swing.*;
import malkawi.login.JTextFieldLimit;
/**
*
* #author Defiledx1
* sign up
*/
public class SignUp extends JFrame implements EventListener {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton complete = new JButton("Next");
JLabel fname = new JLabel("Name: ");
JLabel Mname = new JLabel("Middle Name: ");
JLabel Lname = new JLabel("Last Name: ");
JLabel user = new JLabel("Username: ");
JLabel pass = new JLabel("Password: ");
JLabel info = new JLabel("Click Next to Continue");
JLabel email = new JLabel("Email: ");
JLabel scode = new JLabel("Secret Code: ");
JTextField fname1 = new JTextField();
JTextField Mname1 = new JTextField();
JTextField Lname1 = new JTextField();
JTextField user1 = new JTextField();
JPasswordField pass1 = new JPasswordField();
JTextField email1 = new JTextField();
JTextField scode1 = new JTextField();
JRadioButton showPass = new JRadioButton("Show Pass");
public SignUp() {
super("Sign Up - Flare By Malkawi");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
setResizable(false);
setVisible(true);
setVisible(true);
setLayout(new GridLayout(0, 2, 10, 10));
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
/*
* Limitations
*/
fname1.setDocument(new JTextFieldLimit(10));
Mname1.setDocument(new JTextFieldLimit(1));
Lname1.setDocument(new JTextFieldLimit(10));
user1.setDocument(new JTextFieldLimit(15));
email1.setDocument(new JTextFieldLimit(80));
scode1.setDocument(new JTextFieldLimit(5));
/*
* End Of Limitations
*/
/*
* RadioButton Checked : Unchecked
*/
showPass.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
showPassword(e.getStateChange() == 1 ? true : false);
}
});
/*
* End of RadioButton Checked : UnChecked
*/
/*
* Action of registration
*/
complete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
outPutInformation();
} catch (FileNotFoundException | UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("Flare is unable at the moment!");
}
}
});
/*
* End of Action of registration
*/
// Dimension labelSize = info.getPreferredSize();
/*
* Start of placements
*/
//add(info);
add(fname);
add(fname1);
add(Mname);
add(Mname1);
add(Lname);
add(Lname1);
add(user);
add(user1);
add(pass);
add(pass1);
add(email);
add(email1);
add(scode);
add(scode1);
add(complete);
add(showPass);
add(info);
pack();
}
public void showPassword(boolean showP) {
if (showP == true) {
pass1.setEchoChar((char)0);
} else {
pass1.setEchoChar('*');
}
}
/*
* File Output Requirements
*/
String filename = user1.getText();
String firstname = fname1.getText();
String middlename = Mname1.getText();
String lastname = Lname1.getText();
String username = user1.getText();
#SuppressWarnings("deprecation")
String password = pass1.getText();
String hotmail = email1.getText();
String secretcode = scode1.getText();
/*
* File Output done
*/
public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(filename+".txt", "UTF-8");
writer.println(firstname);
writer.println(middlename);
writer.println(lastname);
writer.println(username);
writer.println(password);
writer.println(hotmail);
writer.println(secretcode);
writer.close();
}
}
the problem is that it's not outputting anything out.
How is it possible to output the file like 2 folder behind
Thank you!
This is not outputting anything because your variables are initialized before entering anything in the text fields. you need to do like this, or directly write textfield values to the file instead if first saving to variables and then writing to file:
public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {
String filename = user1.getText();
String firstname = fname1.getText();
String middlename = Mname1.getText();
String lastname = Lname1.getText();
String username = user1.getText();
#SuppressWarnings("deprecation")
String password = pass1.getText();
String hotmail = email1.getText();
String secretcode = scode1.getText();
PrintWriter writer = new PrintWriter(filename+".txt", "UTF-8");
writer.println(firstname);
writer.println(middlename);
writer.println(lastname);
writer.println(username);
writer.println(password);
writer.println(hotmail);
writer.println(secretcode);
writer.close();
}
I'm writing a simple user log in screen that will store users through serialization. The GUI is fine, and all that's really left is to implement serialization, but I can't get my warningLabel to display text correctly when a user inputs an incorrect password or username. It will display the first error message, but if a different error occurs, the label stays the same. I need the label to change EVERY TIME there is an error. I'll post the whole code below.
UserCreateAccountGUI class:
package userInfoAndSerialization;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class UserCreateAccount implements ActionListener {
public static int numOfUsers;
String username;
String password;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
UserCreateAccount ucaGUI = new UserCreateAccount();
ucaGUI.start();
}
JFrame frame;
JPanel panel;
JTextField usernameField;
JPasswordField passwordField;
JPasswordField confirmPasswordField;
JLabel warningLabel;
public void start() {
frame = new JFrame("Create a new account");
panel = new JPanel();
panel.setLayout(new GridBagLayout());
frame.getContentPane().add(BorderLayout.CENTER, panel);
panel.setBackground(Color.ORANGE);
JLabel userLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
usernameField = new JTextField(15);
passwordField = new JPasswordField(15);
confirmPasswordField = new JPasswordField(15);
GridBagConstraints right = new GridBagConstraints();
right.anchor = GridBagConstraints.WEST;
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.EAST;
right.weightx = (int) 2;
right.fill = GridBagConstraints.REMAINDER;
right.gridwidth = GridBagConstraints.REMAINDER;
// actual GUI
panel.add(userLabel, left);
panel.add(usernameField, right);
panel.add(passwordLabel, left);
panel.add(passwordField, right);
panel.add(confirmPasswordLabel, left);
panel.add(confirmPasswordField, right);
frame.setSize(300, 250);
frame.setVisible(true);
JButton createAccount = new JButton("Create this account");
frame.getContentPane().add(BorderLayout.SOUTH, createAccount);
createAccount.addActionListener(this);
warningLabel = new JLabel();
frame.getContentPane().add(BorderLayout.NORTH, warningLabel);
}
// this is where the problem is.
public void actionPerformed(ActionEvent event) {
if (!(passwordField.getPassword().toString().equals(confirmPasswordField.getPassword().toString()))) {
warningLabel.setText("Your passwords do not match! Please try again!");
} else if (passwordField.getPassword().toString().length() < 1 ) {
warningLabel.setText("Your password is not long enough! Please try again!");
} else if (usernameField.getText().length() < 1) {
warningLabel.setText("Your username is not long enough! Please try again!");
} else {
warningLabel.setText("Account created successfully.");
}
}
}
This isn't going to fly:
passwordField.getPassword().toString().
equals(confirmPasswordField.getPassword().toString())
You'd better print out the results of calling .toString() on a char array to see exactly what I mean.
For instance, when I run:
String fooString = "Foo";
char[] fooArray = fooString.toCharArray();
System.out.println(fooArray.toString());
It does not return "Foo" as you seem to be expecting, but rather the typical and expected toString() representation of a char array: [C#19821f. Note that if you run this, your hashcode number will be different from mine (same if I run this a second time!).
Better to use the Arrays class equals(...) method to let you compare the two char arrays. i.e.,
char[] pw1 = passwordField.getPassword();
char[] pw2 = confirmPasswordField.getPassword();
if (Arrays.equals(pw1, pw2)) {
//...
}
Note: a bad solution would be to translate the char arrays into a "real" String using new String(myCharArray), but I strongly advise against doing this as it makes your passwords very weak and easy to break.