java—在按下按钮时在jtable列中显示和隐藏密码字符

2vuwiymt  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(296)

我试图在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();

             }          
      }
});

这是我在这里的第一篇文章,很抱歉英语不好

yrdbyhpb

yrdbyhpb1#

setText(unmask(length)); 在现实中,无遮掩是徒劳的。您不能仅从lenth恢复密码。
使用 setText(arg1.toString());

相关问题