Question

I'm creating a column in a JTable for passwords.

I'm able to change the cell editor to password editor using the following code:

JPasswordField pwf = new JPasswordField();
    DefaultCellEditor editor = new DefaultCellEditor(pwf);
    jTable1.getColumnModel().getColumn(3).setCellEditor(editor);

I'm not able to figure out correct solution for rendring the password field content with the same behavoir as JPassword control. By default, its rendering the text entered and displaying it. How to override it, so that the renderer will render only displays the "*" or black dot with the same length as password entered.

Thanks, Chandra

Update 1: Currently I'm using password field renderer given below:

class PasswordCellRenderer extends JPasswordField
implements TableCellRenderer {

    public PasswordCellRenderer() {
        super();
        // This displays astericks in fields since it is a password.
        // It does not affect the actual value of the cell.
        this.setText("filler123");
    }

    public Component getTableCellRendererComponent(
    JTable arg0,
    Object arg1,
    boolean arg2,
    boolean arg3,
    int arg4,
    int arg5) {
        return this;
    }
}

Calling the above renderer using:

jTableJDBCPools.getColumnModel().getColumn(3).setCellRenderer(new PasswordCellRenderer());

This renderer is masking eventhough the password field is empty. So its difficult for a user to find out whether a password cell is empty or filled (since its always shows some masked content).

How to wrire a renderer which keeps blank when nothing is entered in password field and when something is entered in the password field, it must show the length of the characters entered in the password field ?

Was it helpful?

Solution

You need to set a dedicated cell renderer for that column using setCellRenderer that will return a masked version of the password. See more information in Oracle's tutorial.

EDIT

Something along those lines:

class PasswordCellRenderer extends DefaultTableCellRenderer {

    private static final String ASTERISKS = "************************";

    @Override
    public Component getTableCellRendererComponent(JTable arg0, Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {
        int length =0;
        if (arg1 instanceof String) {
            length =  ((String) arg1).length();
        } else if (arg1 instanceof char[]) {
            length = ((char[])arg1).length;
        }
        setText(asterisks(length));
        return this;
    }

    private String asterisks(int length) {
        if (length > ASTERISKS.length()) {
            StringBuilder sb = new StringBuilder(length);
            for (int i = 0; i < length; i++) {
                sb.append('*');
            }
            return sb.toString();
        } else {
            return ASTERISKS.substring(0, length);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top