how to peek password while typing in JPasswordField - java

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.

Related

Log in form and text file [closed]

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.

Trying to make a login page, I am stuck! [java] [duplicate]

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");
}
}

user input for JLabel

I have a problem with a piece of code. When I click on it in my GUI, it reopens once I've inputted text. Can anyone explain to me what is wrong with the code. I'm using this to set a name in a JLabel in my GUI
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom" + "baker";
usernameinput = JOptionPane.showInputDialog(
setNameButton, "Enter a username",
"Set username", JOptionPane.OK_CANCEL_OPTION);
{
username.setText(String.valueOf(usernameinput));
}
});
I've created a simple GUI to test your code and the dialog opens just once.
I have cleaned up a bit your listener, but basically it's the same code.
Your problem may be in another part of your code.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleFrameTest extends JFrame {
JLabel username = new JLabel("Press button to enter your name here");
public SimpleFrameTest() {
setSize(300, 300);
setTitle("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
initComponents();
setVisible(true);
}
private void initComponents() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
username.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton setNameButton = new JButton("Set name");
setNameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput = JOptionPane.showInputDialog(setNameButton, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
if (usernameinput != null) {
username.setText(String.valueOf(usernameinput));
}
});
panel.add(Box.createRigidArea(new Dimension(5,10)));
panel.add(username);
panel.add(Box.createRigidArea(new Dimension(5,10)));
panel.add(setNameButton);
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleFrameTest();
}
});
}
}
your code is behaving like that because of this
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom"
+ "baker";
usernameinput = JOptionPane.showInputDialog(null,
as you can see, the JOptionPane.showInputDialog(setNameButton is taking the setNameButton as a parameter so you are in some kind of recursive infinite loop
use another button for the modalDialog:
Example:
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom"
+ "baker";
usernameinput = JOptionPane.showInputDialog(null, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
{
username.setText(String.valueOf(usernameinput));
}
});

Why won't my log in user GUI set the warning label correctly?

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.

Getting rid of Dialog Boxes and replacing with JLabel

I am currently working on an applet and am having a bit of trouble finishing it off. My code works just fine however I need to change the final portion from a JOptionDialog Message Dialog into just a JLabel that gets added to the applet. I've tried every way I can think of and am still coming up short. My current code looks as followed:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
JOptionPane.showMessageDialog(null, "Access Granted");
return
}
else {
JOptionPane.showMessageDialog(null, "Access Denied");
}
}
}
}
Please help!
Try this one:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
JLabel message = new JLabel();
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.add(message);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
message.setText("Access Granted");
return;
}
else {
message.setText("Access Denied");
}
}
}
}
Its sample code so no alignment is done it will show message next to button. You can change alignment as you wish ;)

Categories