Roman Dorokhov Roman Dorokhov - 5 months ago 13
Java Question

JTable cloumn doesn't get focused anymore

Recently I have a small problem with one column in a JTable: since I edited it's DefaultTableCellRenderer the password column doesn't get focused, when I focus a row in the table. Here's a screenshot an my code:

inputsTable.getColumn("Passwort").setCellRenderer(new DefaultTableCellRenderer(){

private final String ASTERISKS = "*";
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
int length =0;
if (value instanceof String) {
length = ((String) value).length();
} else if (value instanceof char[]) {
length = ((char[])value).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);
}
}
});


I have already tried some different options, but they didn't help me, unfortunately. Does anyone of you have eventually a clue, is there maybe some better implementation of a password column in a JTable without this problem? Thanks in advance!

Answer

The DefaultTableCellRenderer implementation posted sets no formatting based upon the current state (in particular the isSelected parameter). To keep default formatting, consider calling the parent method prior to your customization.

                public Component getTableCellRendererComponent(JTable table,
                                                               Object value,
                                                               boolean isSelected,
                                                               boolean hasFocus,
                                                               int row,
                                                               int column) {
                    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
                    //do your customization here
                }
Comments