Masking Password Data in Non-editable Cells

Suppose you want to store password values in a table, but you don’t want that password data to be displayed. While there are other ways to accomplish this, masking the password fields makes the logic to maintain the data easier.

The code below initializes individual columns in a table. It determines in the method if the cell is a password field by looking at the column heading:

/*** This method sets column sizes and cell renderers.**/private void initColumns(JTable table) {   XMLTableModel model = (XMLTableModel)table.getModel();   TableColumn column = null;   Vector longValues = model.columnNames;   TableCellRenderer headerRenderer =        table.getTableHeader().getDefaultRenderer();   for (int i = 0; i < longValues.size(); i++) {            // Format other column names ....            // Set password field to hide data	      if(column.getHeaderValue().equals("Password")){	  column.setCellRenderer(new PasswordCellRenderer());      }   }}

If the cell is a password field, the code sets the cell renderer for the cell to the class, like in the code below. Setting the text to any value renders asterisks in the field because it extends the JPasswordField class. It does not affect the actual value of the cell, but masks the password data.

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;   }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: