Question

I have an assignment question that requires me to create a JPasswordField. Two buttons are needed, one to show the actual password in another textfield, and the other just shows the character count in the textfield. Here's what I have to far, but I can't get it to compile because Method setText in class javax.swing.text.JTextComponent cannot be applied to given types. The compiler stops under bt1 when I want it to read the password itself.

Can anyone help?

Thanks. Code:

public class JavaPasswordCount {  
    public JavaPasswordCount() {
        JFrame window = new JFrame("Password Character Count");
        window.setSize(50, 50);
        JButton bt1 = new JButton("Show Count");
        JButton bt2 = new JButton("Show Password");
        final JPasswordField pwd = new JPasswordField();
        final JTextField tf = new JTextField(); 
        final int counter;

        JPanel panel = new JPanel(); 

        bt1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                tf.setText(pwd.getPassword());
            }
        });

        bt2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                counter = pwd.length();
                tf.setText(counter);
            }
        });

        panel.setLayout(new FlowLayout()); // Add buttons and TextField to the panel
        panel.add(tf);
        panel.add(pwd);
        panel.add(bt1);
        panel.add(bt2);

        window.getContentPane().add(panel, BorderLayout.CENTER);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.pack();
        window.setVisible(true);
    }
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {
        }

        JavaPasswordCount application = new JavaPasswordCount();
    }
}
Was it helpful?

Solution

Change this lines:

counter = pwd.length();
tf.setText(counter);

to

int counter = pwd.getPassword().length;
tf.setText(String.valueOf((counter)));

and this

tf.setText(pwd.getPassword());

To

tf.setText(pwd.getPassword().toString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top