Hide data with JOptionPane

How to hide characters using the showInputDialog panel of the JOption. For example: JOptionPane.showInputDialog ("Enter your name:").

I want to hide characters when the user gives his name. I was in the middle of the application. If I hide these characters, my work will be done. I do not want to use JPasswordField, since it requires a form to store this tag (JPasswordField).

+6
source share
3 answers
public static String getName() { JPasswordField jpf = new JPasswordField(24); JLabel jl = new JLabel("Enter Your Name: "); Box box = Box.createHorizontalBox(); box.add(jl); box.add(jpf); int x = JOptionPane.showConfirmDialog(null, box, "Name Entry", JOptionPane.OK_CANCEL_OPTION); if (x == JOptionPane.OK_OPTION) { return jpf.getText(); } return null; } 
+3
source

You can use JPasswordField, which by default replaces the characters '*'.

You can read the following:

Why does JPasswordField.getPassword () create a string with a password in it?

And if you are looking for an alternative to JPasswordField, you can read this:

Is there an alternative to JPasswordField?

+1
source

Here's a solution that uses JOptionPane to display a JPasswordField that prints spaces as the user types.

Indeed, all you would like to put in your code is the showPasswordPrompt() method, but the code includes the main() method, which allows you to easily check how the dialog box looks.

 import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPasswordField; public class JOptionPaneTest { public static String showPasswordPrompt( Component parent, String title ) { // create a new JPasswordField JPasswordField passwordField = new JPasswordField( ); // display nothing as the user types passwordField.setEchoChar( ' ' ); // set the width of the field to allow space for 20 characters passwordField.setColumns( 20 ); int returnVal = JOptionPane.showConfirmDialog( parent, passwordField, title, JOptionPane.OK_CANCEL_OPTION ); if ( returnVal == JOptionPane.OK_OPTION ) { // there a reason getPassword() returns a char[], but we ignore this for now... // see: http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords return new String( passwordField.getPassword( ) ); } else { return null; } } public static void main( String[] args ) { final JFrame frame = new JFrame( ); final JButton button = new JButton( "Push Me For Dialog Box" ); button.addActionListener( new ActionListener( ) { @Override public void actionPerformed( ActionEvent e ) { String password = showPasswordPrompt( frame, "Enter Password:" ); button.setText( password ); } } ); frame.add( button ); frame.setSize( 400, 400 ); frame.setVisible( true ); } } 
+1
source

Source: https://habr.com/ru/post/911931/


All Articles