Set PlaceHolder on JPasswordField - java

I am developing a system with Java (using NetBeans) and, to make it more "professional", I've added some cool functions, such as Placeholders (Yes, I know, it's from HTML).
For ALL the JTextFields I have, I've used the following code to generate their placeholders (The name of the JTextField in this example is "tfUser") :
private void tfUserFocusGained(java.awt.event.FocusEvent evt) {
if (tfUser.getText().equals("Your User Name...")) {
tfUser.setText("");
tfUser.setForeground(Color.BLACK);
}
}
private void tfUserFocusLost(java.awt.event.FocusEvent evt) {
if (tfUser.getText().equals("")) {
tfUser.setText("Your User Name...");
tfUser.setForeground(Color.GRAY);
}
}
It's a "focus match":
The Text Field has initially the text "Your User Name...", with a "GRAY" foreground. Every time this text field gains the focus, it verifies its text: if the text.equals("Your User Name..."), its text is set to "" (An empty String) and the Foreground is set to BLACK (default). On the other hand, if the text.equals("Anything else..."), it means that the user has probably inserted the user name, so, do not do anything with this code.
Every time the text field loses the focus, it verifies its text: if the text.equals("") (An empty String again), its text is set back to "Your User Name..." and the Foreground is set to GRAY. And again, if the text.equals("Anything else..."), it means that the user has probably inserted the user name, so, do not do anything with this code.
This code is working perfectly with the JTextFields But, when I do the same with JPasswordFields, I get the following result:
****************
(It should be "Your Password...")
Can anyone help me to add a placeholder to this JPasswordField? Thanks in advance.

What i did for my login code was add a checkbox that "shows password" and in the jframe i added this statement:
//Setting checkbox selected to true so the word "password" is seen when program runs
passCheckBox.setSelected(true);
if(passCheckBox.isSelected())
{
PasswordField.setEchoChar((char)0);
}`
Code for password checkbox:
if(passCheckBox.isSelected())
{
PasswordField.setEchoChar((char)0);
}else{
PasswordField.setEchoChar('*');
}
Code for Password Field Focus Gained:
private void PasswordFieldFocusGained(java.awt.event.FocusEvent evt) {
passCheckBox.setSelected(false);
PasswordField.setEchoChar('*');
String password = String.valueOf(PasswordField.getPassword());
if(password.toLowerCase().equals("password"))
{
PasswordField.setText("");
PasswordField.setForeground(Color.black);
}
}
Code for Password Field focus lost:
private void PasswordFieldFocusLost(java.awt.event.FocusEvent evt) {
String password = String.valueOf(PasswordField.getPassword());
if(password.toLowerCase().equals("password") || password.toLowerCase().equals("") )
{
PasswordField.setText("Password");
PasswordField.setEchoChar((char)0);
PasswordField.setForeground(new Color(153, 153, 153));
}
}
I kinda did half of this on my own and took some bits from videos i hope this helps :>

Here is my method for getting the placeholders
private void getPlaceholders(JTextField text) {
String temp = text.getText();
text.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
text.setText("");
text.setForeground(Color.BLACK);
}
#Override
public void focusLost(FocusEvent e) {
if (text.getText().isEmpty()) {
text.setForeground(Color.GRAY);
text.setText(temp);
}
}
});
}
Here is how i implemented it.
// Password Field
passwordField = new JPasswordField();
passwordField.setBounds(48, 340, 288, 32);
roundedPanel.add(passwordField);
passwordField.setText("Password");
passwordField.setEchoChar((char) 0);
getPlaceholders(passwordField);
what allows you to see placeholders in passwordFields is
passwordField.setEchoChar((char) 0);
you can take it out to use in regular text fields

Related

How can this java code display an output in BlueJ?

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.

How to disable jTextfield again when the other jTextfield is empty in java

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.

setDefaultButton not working as expected

public JoinChatClient(String serverAddress, String chatName)
{
chatWindow.getContentPane().add(sendButton, "South");
chatWindow.getContentPane().add(splitPane, "Center");
chatWindow.setSize(800,500);
sendButton.addActionListener(this);
chatWindow.setTitle("Chat Room");
chatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
splitPane.setDividerLocation(350);
sendButton.setBackground(Color.gray);
sendButton.setForeground(Color.red);
outChatTextArea.setEditable(false);
inChatTextArea.setFont (new Font("default",Font.ITALIC,20));
outChatTextArea.setFont(new Font("default",Font.BOLD,20));
inChatTextArea.setLineWrap(true);
outChatTextArea.setLineWrap(true);
inChatTextArea.setWrapStyleWord(true);
outChatTextArea.setWrapStyleWord(true);
inChatTextArea.setText("Enter text to be sent here.");
outChatTextArea.setText("You can move the separator bar!");
inChatTextArea.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if(inChatTextArea.getText().equals("Enter text to be sent here."))
{
inChatTextArea.setText("");
inChatTextArea.setFont(new Font("default",Font.BOLD,20));
}
}
public void focusLost(FocusEvent e) {
if(inChatTextArea.getText().isEmpty())
{
inChatTextArea.setFont (new Font("default",Font.ITALIC,20));
inChatTextArea.setText("Enter text to be sent here.");
}
}
});
chatWindow.getRootPane().setDefaultButton(sendButton);
chatWindow.setVisible(true);
}
I've looked over all the threads I could find concerning this, and I cannot figure out why hitting ENTER doesn't activate the actionPerformed method attached to sendButton. Is it because the text field has a FocusListener?
Things I've tried:
changing the statement to target the specific text field (inChatTextArea)
moved the setVisible statement to the end
targeted different parts of the GUI when hitting enter
Bear in mind I've only included the code that builds the GUI in an attempt to waste less of your time.
What I want: Ideally, I want to keep my FocusListener (or something like it) so that I can display the "text field hint." I would like to be able to hit ENTER to send the user's text while the inChatTextArea field is focused.
If a component on the JFrame has focus, and can accept an enter key press, such as one of the JTextAreas, then the enter presses will go to that component and not to the default button. For the default button to work, then the JFrame or the button or some other component that does not accept enter key presses, needs to have focus. I'm guessing that one of your JTextAreas has stolen the focus, and that this is messing you up.
This question is old, but I found it when having the same issue. So I hope others might find it useful.
I figured out that getRootPane() will return null if the component is trying to access the root pane too early, e.g. under construction of the component.
Hence, I propose to use SwingUtilities.invoke(Runnable) to postpone setting the default button on the root pane, and also to request the focus to the button.
So this method could be a helper method on a class to extend from:
protected void setDefaultButton(JButton button) {
// Uses invoke later, as getRootPane() might return null if the method is called under construction
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JRootPane rootPane = getRootPane();
if (rootPane != null) {
rootPane.setDefaultButton(button);
}
button.requestFocus(); // set the focus on the button
}
});
}

"Concatenating" andFilter and orFilter for RowFilter

I have a JTable with four columns, the first one containing either a number or a text, the other three only text. I'm trying to filter this table with the help of a RowFilter:
sorter = new TableRowSorter<TableModel>(myOwnTableModel);
The checkboxFilter I got works well enough:
sorter.setRowFilter(RowFilter.regexFilter("^[0-9]$", 0));
This sorter is activated or deactivate depending on a checkbox that is either set or not.
The second filtering happens if a user puts some text in a textfield. For itself, this works fine already:
String regex = "(?i)" + Pattern.quote(s); // s = input Text of user
sorter.setRowFilter(RowFilter.regexFilter(regex, 1,2,3));
What I can't do, is to activate both filters at the same time. Maybe I'm thinking way too far, my idea has been to "concatenate" the two filters, the checkboxFilter should be "and" the other "or". I tried several things, to me the most promising looked something like:
String regex = "(?i)" + Pattern.quote(s);
bookFilter = RowFilter.regexFilter(regex, 1,2,3);
sorter.setRowFilter(bookFilter.andFilter(Arrays.asList(
RowFilter.regexFilter("^[0-9]$", 0))));
Unfortunately, this doesn't lead to any usable result. Any ideas appreciated :)
The solution is to add an ActionListener to the JCheckBox to update the filter state if the checkbox is toggled and to add a DocumentListener to the JTextField's underlying Document to update the filter state if the contents of the field is updated.
The other bug in your code is that you are calling the static andFilter method on your bookFilter instance and are only passing in the newly constructed regex filter (i.e. you are only passing in one parameter to andFilter). The correct usage is:
RowFilter andFilter = RowFilter.andFilter(filter1, filter2, etc);
Example Event Listeners
JCheckBox cb = ...
cb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
updateFilters();
}
});
JTextField tf = ...
tf.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { updateFilters(); }
public void removeUpdate(DocumentEvent e) { updateFilters(); }
publci void changedUpdate(DocumentEvent e) { updateFilters(); }
});
... and then define your updateFilters() method to install a new filter based on when the checkbox is selected and whether the text field is empty or not.
Example Filter Update Method
public void updateFilters() {
if (cb.isSelected()) {
if (tf.getText().length() > 0) {
// Both filters active so construct an and filter.
sorter.setRowFilter(RowFilter.andFilter(bookFilter, checkBoxFilter));
} else {
// Checkbox selected but text field empty.
sorter.setRowFilter(checkBoxFilter);
}
} else if (tf.getText().length() > 0) {
// Checkbox deselected but text field non-empty.
sorter.setRowFilter(bookFilter);
} else {
// Neither filter "active" so remove filter from sorter.
sorter.setRowFilter(null); // Will cause table to re-filter.
}
}

Java - change focus on key press

I am writing a Java Application for Data Entry using Eclipse and SWT. Naturally it has a great many Text objects.
What I would like to happen is that when user enters something into one field focus automatically changes to the next field.
Thanks in advance
final Text textBox = new Text(shell, SWT.NONE);
textBox.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (x.getText().length() == 1); {
x.traverse(SWT.TRAVERSE_TAB_NEXT);
}
}
});
final Text textBox = new Text(shell, SWT.NONE);
textBox.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
if (textBox.getText().equals("") == false) {
textBox.traverse(SWT.TRAVERSE_TAB_NEXT);
}
}});
You may also want to have a look at the VerifyListener interface. See this interesting blog post for a caveat though: http://eclipsenuggets.blogspot.com/2008/10/eclipse-bug-patterns-selfish-validation.html
I assume you want to change the focus after the field has been filled. I suggest using a DocumentListener (or whatever SWT calls it) to be notified of changes to the field's content: if it has the right number of characters, jump to the next field.

Categories

Resources