Reputation: 47
So I need to know is there a way to show the final password of this code to jTextField control, cuz when I tried I got issue char couldnt convert to String.
import java.util.Random;
Random r = new Random();
String alphabet = "qwertyuiopasdfghjklzxcvbnm";
for (int i = 0; i < 50; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
Upvotes: 0
Views: 310
Reputation: 4146
If you are trying to provide secure random-generated password use SecureRandom with proper methdos. Please refer to this. I do not have any articles about it in english, but if you could get on with some translator please read this one to see how one could hack such algorithm.
EDIT:
More on difference between Random
and SecureRandom
Upvotes: 0
Reputation: 9650
Random r = new Random();
String alphabet = "qwertyuiopasdfghjklzxcvbnm";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < 50; i++) {
buf.append(alphabet.charAt(r.nextInt(alphabet.length())));
}
jTextField.setText(buf.toString());
Upvotes: 1
Reputation: 2489
Currently in your code you are just generating the characters randomly and printing it. You need to form a String
from all these generated Characters and then you can set it as a Text in a TextField
.
You can have a StringBuilder
which gets appended with every random character
.
String alphabet = "qwertyuiopasdfghjklzxcvbnm";
StringBuilder password=new StringBuilder();
for (int i = 0; i < 50; i++) {
password.append(alphabet.charAt(r.nextInt(alphabet.length())));
}
String password_str=password.toString();
System.out.println(password_str);
Suppose that you have a JTextField
then you can set there password_str as its value.
JTextField password_field = new JTextField();
password_field.setText(password_str);
Upvotes: 1