我按下按钮时试图在jtable列中隐藏和显示密码,我按下按钮时隐藏了密码,但当再次按下时,列变为空 这是我的代码:
private String mask(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append('\u25CF');
}
return new String(sb);
}
private String unmask(int length){
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append('\0');
}
return new String(sb);
}
masked=new DefaultTableCellRenderer(){
private static final long serialVersionUID = 1L;
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(mask(length));
return this;
}
};
unmasked=new DefaultTableCellRenderer(){
private static final long serialVersionUID = 1L;
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(unmask(length));
return this;
}
};
现在按钮代码:
//i have a global variable set to false,to detect if password is show
boolean show=false;
JButton showpass=new JButton("Show password");
showpass.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(show==false){
show=true;
data.getColumnModel().getColumn(3).setCellRenderer(unmasked);//data it's the jtable
tmodel.fireTableDataChanged();//tmodel it's the jtable model
}else if(show==true){
show=false;
data.getColumnModel().getColumn(3).setCellRenderer(masked);
tmodel.fireTableDataChanged();
}
}
});
这是我在这里发表的第一篇文章,对不起英文不好
答案 0 :(得分:1)
setText(unmask(length));
是徒劳的。您无法仅从lenth恢复密码。
使用setText(arg1.toString());