0

I'm using Jython and trying to get the user to input a password. However, I would like it to show an asterisk rather than the characters that the user is inputting. I managed to do something similar using getpass, but it required you to type into the cmd line, and it would just not show anything rather than an asterisk.

I'm looking to have the user type into a dialog box; the "input()" command brings up a box that would be perfect. For example, this:

import sys

password = input("Please enter your password: ")
if password == None:     #if the user hits cancel
    sys.exit(0)

However, it does not mask the text. I am able to do this using the java aspect of jython like so:

import javax.swing.JOptionPane as JOP
import javax.swing.JPasswordField as JPF
import sys

pwdF = JPF()
choice = JOP.showConfirmDialog(None, pwdF,
    "Please enter your password:",
    JOP.OK_CANCEL_OPTION)

if choice == JOP.CANCEL_OPTION:
    sys.exit(0)
password = pwdF.getText()

A problem I have with this is that I can't get the cursor to default to the text field (instead it starts on the ok button). Primarily, though, I'd like a more pythonic way of doing this.

I messed around quite a bit with java.swing, using layout and add components; however, I didn't understand it enough to tweak it in a way that would work.

Does anyone know a method of creating an input box with masked text different from the java version I posted?

Thanks.

user2869231
  • 1,431
  • 5
  • 24
  • 53

1 Answers1

0

You can use javax.swing.JPasswordField class. An example is this :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class PwdForm extends JFrame {
    public JFrame frame;

    public PwdForm() {

        //Create main Panel 
        JPanel mainPanel = new JPanel();

        //Password field
        JLabel lblPwd = new JLabel("Password :");
        mainPanel.add(lblPwd);
        final JPasswordField txtPwd = new JPasswordField(20);
        lblPwd.setLabelFor(txtPwd);
        mainPanel.add(txtPwd);

         //Confirm Button
         final JButton btnOk = new JButton("Confirm");
         mainPanel.add(btnOk);

         //Create and set up the window.
         frame = new JFrame("Password Example");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         //Set up the content pane.
         mainPanel.setOpaque(true);  //content panes must be opaque
         frame.setContentPane(mainPanel);

        //Display the window.
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
         PwdForm lf = new PwdForm();    
    }
}