Hide/Show Password in a JTextFIeld (Java Swing) - java

So I've been working on a Password Strength Checker and the way it works is that the user enters some random text into a textfield and then instantaneous visual feedback (breakdown of points) is displayed. I've also added a checkbox, which on being selected, should hide the password i.e. replace all the chars with asterisks, while preserving the actual text input by the user. A document listener is being used to keep track of changes inside the textfield. (each char on entry gets analyzed and then scored)
So, my question is, how exactly do I mask the user input with asterisks preserving its original value?
Here's what the GUI looks like:
http://speedcap.net/sharing/screen.php?id=files/51/2f/512f9abb3f92a25add7c593e9d80e9e4.png

How exactly do I mask the user input with asterisks preserving its original value?
Use the JPasswordField which has nice function jPasswordField.getPassword(); to get the password as char[] to work with.
Use jPasswordField1.setEchoChar('*') to mask the password characters with *.
If you wish to see the value you are inserting use jPasswordField1.setEchoChar((char)0); Setting a value of 0 indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField.
Tutorial and Reference:
How to use Password Fields
setEchoChar(char)

Use Password Field Instead of using textfield

ok thanks for tutorialnya,
and ex,
action chechbox / double click
private void lihatActionPerformed(java.awt.event.ActionEvent evt) {
if (lihat.isSelected()) {
password.setEchoChar((char)0); //password = JPasswordField
} else {
password.setEchoChar('*');
}
}

I solved it as follows:
if ( jPasswordField.getEchoChar() != '\u0000' ) {
jPasswordField.setEchoChar('\u0000');
} else {
jPasswordField.setEchoChar((Character) UIManager.get("PasswordField.echoChar"));
}

Related

If Statement Providing Wrong Output

I coded a banking program. I'm at the point where the user must enter their pin, and it must be compared to their pin which is taken from a text file. The problem is, I have an if statement, and the condition is met, but it keeps giving me an the statement as if it was not met.
I've tried switch statements and even using a boolean value, but it does not work
public String getPin(){
return pin;
}
String pin2 = lbl_Pin.getText();
System.out.println(pin2);
System.out.println(getPin());
// Allows the user to select what they want to do after they enter the
// correct pin
if (pin2.equals(String.valueOf(getPin()))) {
btn_SelectLoan.setEnabled(true);
btn_SelectWithdraw.setEnabled(true);
btn_SelectDeposit.setEnabled(true);
btn_Balance.setEnabled(true);
lbl_Loan.setVisible(true);
lbl_Withdraw.setVisible(true);
lbl_Deposit.setVisible(true);
lbl_Balance.setVisible(true);
}
// Displays invalid if the pin is not correct
else {
lbl_Pin.setText("Invalid");
}
I enter the correct pin, I am sure of this as I displayed the correct pin as well as the entered pin, and they are the same, but an invalid answer is provided
It might be an encoding issue. When you are reading the pin from the text file, please make sure that the encoding of the text matches with that of lblP=_Pin.
When you are reading the text file, you can mention the desired encoding while opening the file.
I found the issue. When getting the Pin from the text file, '/r' was added on as part of the value. So I just made a substring with the actual value of the pin.

Disabling a button in Netbeans GUI until correct password is put into the password field

I'm very new at coding, and I want a swing button in the netbeans GUI to stay disabled until the correct password is entered to a password field. I have already created the password field, and given it a correct password.
If you can keep it simple it would be appreciated, as I'm very new to programming in general.
You can make use of setEnabled property,
button.setEnabled(true);
you can set it to false initially , upon validating make it true .
if (text.equals("password"))
button.setEnabled(false);
As #setEnabled(boolean),
Enables or disables this component, depending on the value of the parameter b. An enabled component can respond to user input and generate events. Components are enabled initially by default.
You should first set the button to setEnabled(false) and then make a new method, to check if the password in the field is correct such as this:
public void check()
{
boolean c = true;
while(c){
if(pf.getText().equals(correct_password)) c = false;
}
button.setEnabled(true);
}
And you should run this method in a new Thread, so that it does not freeze your GUI.
When the password will be correct, then it will be enabled.
P.S. I know that using getText for a Password Field is deprecated by getPassword(), but for the sake of simplicity, I have used getText() here.
Try this
jButton1.setEnabled(false)
String text = jTextField.getText();
Into Thread
if (text.contains("password"))
jButton1.setEnabled(true);
put the If statement code in thread and set the thread delay to 2sec (2000ms)

Prevent typing in the same style in JTextPane

forgive me for a possible misleading title, but the problem is a bit hard to describe.
I'm currently trying to create a basic texteditor using a JTextPane in Java and I've run into an issue.
As you know in most texteditors you can put your caret/cursor behind a piece of styled text (for example text which is bold) and then you can continue typing in that same style (Eg. append more bold characters).
Luckely this is present by default in the JTextPane, but I want to disable it for a certain style. Mainly the URL-style I coded (basicly this one just sets the HTML.Attribute.HREF attribute in the style to an URL).
So if I would put my caret behind a word (or piece of text) which is an URL, I want to ensure that the next characters which will be added, will not be in the URL-style.
Eg. I think tinymce has this behaviour:
You select text
Click on the Insert URL button
Insert the URL
Place the cursor right after the URL and start typing again in normal style
Is there a way to enforce this behaviour in a JTextPane?
I was thinking about something like this:
Adding a listener for content changes in the document
Check if the added characters were placed right behind a piece of text with the URLstyle
If that was the case => remove the "href" attribute from the style of those characters
The code i use for setting the URL-style to the selected text can be found below. "dot" and "mark" are retrieved from the caret.
SimpleAttributeSet attr = new SimpleAttributeSet(doc.getCharacterElement(dot).getAttributes());
StyleConstants.setUnderline(attr, true);
StyleConstants.setForeground(attr, Color.BLUE);
attr.addAttribute(HTML.Attribute.HREF, url);
doc.setCharacterAttributes((dot < mark) ? dot : mark, length, attr, true);
(Note: To be able to tell the difference between normal "blue underlined" text and an URL, the HREF attribute is used for an URL.)
PS: This is my first question here, so hopefully I gave enough information. ;)
Language: Java, JDK 1.7
Thanks in advance.
Add a CaretListener to detect move and check whether current caret position needs the style reset. If it's detected use
StyledEditorKit's method
public MutableAttributeSet getInputAttributes()
Here just remove the attributes you don't need (URL, blue, underline).
I thought I'd share my solution to the problem (found with the help of StanislavL's answer - thanks again for putting me on the right track).
The following method is called from within a caretlistener, passing the attributes found via the "getInputAttributes"-function and the dot and mark of the caret.
private void blockURLTyping(MutableAttributeSet inputAttr, int dot, int mark)
{
StyledDocument doc = getStyledDocument();
int begin = (dot < mark) ? dot - 1 : mark - 1;
if(begin >= 0)
{
Element dotEl = doc.getCharacterElement(begin);
Element markEl = doc.getCharacterElement((dot < mark) ? mark : dot);
AttributeSet dotAttr = dotEl.getAttributes();
AttributeSet markAttr = markEl.getAttributes();
if(dotAttr.isDefined(HTML.Attribute.HREF)) // Ensure atleast one of them isn't null
{
if(dotAttr.getAttribute(HTML.Attribute.HREF) == markAttr.getAttribute(HTML.Attribute.HREF))
{
inputAttr.addAttribute(HTML.Attribute.HREF, dotAttr.getAttribute(HTML.Attribute.HREF));
inputAttr.addAttribute(StyleConstants.Foreground, Color.BLUE);
inputAttr.addAttribute(StyleConstants.Underline, true);
return;
}
}
}
if(inputAttr.isDefined(HTML.Attribute.HREF)) // In all other cases => remove
{
inputAttr.removeAttribute(HTML.Attribute.HREF);
inputAttr.removeAttribute(StyleConstants.Foreground);
inputAttr.removeAttribute(StyleConstants.Underline);
}
}
Important note; The inputAttributes do not update when the caretposition changes but stays within the same element.
So: when the caret is positioned at the end of the URL, behind the last character => you remove the three attributes you can see in the code above => However when the caret is moved to another position within the URL, the attribute stays removed because the set does not update.
So in practice this means that when you remove attributes from the attributeset, they will stay removed untill the StyledEditorKit updates the inputattributes.
To work around this problem I decided to add the attributes again if the caret is in the middle of an URL, allowing you to insert characters in the middle of the URL - but not append or prepend characters (like I wanted).
The code can probably be optimized a bit more because in most cases dot==mark, but I wanted to share this solution.
PS: The comparison of the HREF-attributes is to deal with the situation where two different URLs are positioned next to eachother in a text. It basicly should check if they are both different instances of a certain object even if the URL itself might be the same.
Code that calls this function:
#Override
protected void fireCaretUpdate(CaretEvent e)
{
super.fireCaretUpdate(e);
MutableAttributeSet attr = getStyledEditorKit().getInputAttributes();
int dot = e.getDot();
int mark = e.getMark();
blockURLTyping(attr, dot, mark);
...
}

Vaadin Checkbox -- Add a newline on caption

I am trying to set the caption of a checkbox and i want to break at a certain point in the string to create a new line without waiting for the word wrap:
When i added the simple \n character to caption string it did not work.
private CheckBox completeCheckbox;
completeCheckbox.setCaption("why wont this\n break");
I just had the same problem and the simple solution for this was to call "setCaptionAsHtml(true)" on the CheckBox instance and to set the caption using HTML code.
private CheckBox completeCheckbox = createMyCheckboxSomehowFunction();
completeCheckbox.setCaptionAsHtml(true);
completeCheckbox.setCaption("why wont this<br/>break");
The above code snippet should do what you want. At least it worked fine for me.
i think the solution is to use an Option Group
I just read that here

IPhone password field in AWT/SWT?

I want to create a special Password Dialog for my eclipse product, which is used with an on screen keyboard.
It would be very nice, if i could use a component like the IPhone Password field. In this field, the added character is shown for a second and after the second it is converted into the '*' character for hiding the complete password.
Did a jar/library exists, this is implemented in AWT or SWT?
Edit:
I could trying to implement it from scratch (SWT), but for these i would have to create a very special and complicated KeyListener for the password Text component. I would have to catch the keyReleased event and set the characters manually into the field.
So far i was not able to find any libraries in the web. Suggestion how this can be implemented are welcome too.
This is not really a full answer, rather than a discussion starter and I don't know of any out-of-the-box widgets which can do that.
My first idea was to inheriting the swt Text widget and overriding setEchoChar et al., but after looking at the code this doesn't really seem feasible, because this method is merely a wrapper around:
OS.SendMessage (handle, OS.EM_SETPASSWORDCHAR, echo, 0);
If anyone would know the OS specific low-level implementation, that might be helpful.
Anyway, on to a different approach. I would avoid the KeyListener and use a ModifyListener on the Text-Widget.
void addModifyListener(ModifyListener listener)
You could then build a wrapper which catches the entered text using this listener, appends it to a locally held string/stringbuffer (or e.g. the Eclipse Preferencestore) and send a modified full text to the Text widget using setText(String s), replacing all characters except the last by an echo character (e.g. *).
myText.setText((s.substring(0, s.length()-1)).replaceAll("[\\s\\S]","*")+s.charAt(s.length()-1));
This is a bit of a kludge, but it should work.
The not so straightforward bit is the 1 second timing, without stalling the whole view...
Depending on what Jules said the following code is some kind of working.
The code is quick and fast and i would like to have a more thread safe solution.
originalString = new StringBuffer();
passwordField.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
synchronized (passwordField) {
String s = passwordField.getText();
String newS = s.replaceAll("[\\s\\S]", "*");
if (newS.equals(s)) {
while (originalString.length() > s.length()) {
originalString = originalString.deleteCharAt(originalString.length() - 1);
}
usernameField.setText(originalString.toString());
return;
}
if (originalString.length() < s.length()) {
originalString.append(s.charAt(s.length() - 1));
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
}
passwordField.setText(newS);
}
passwordField.redraw();
passwordField.setSelection(passwordField.getText().length());
}
});
Key Events are cached, so you can add more characters, also when the Thread is waiting.
Another Problem is the Cursor handling. the Cursor always moves to the first position, when you set the Text.
I think when this is working it is very near to the iphone solution.

Categories