2013-03-31 45 views
1

我有一個任務需要我創建一個JPasswordField。需要兩個按鈕,一個用於在另一個文本框中顯示實際密碼,另一個僅顯示文本框中的字符數。這是我的目標,但我無法編譯它,因爲Method setText in class javax.swing.text.JTextComponent cannot be applied to given types. 編譯器在bt1下停止,當我希望它自己讀取密碼時。Java - 密碼字段字符計數器

任何人都可以幫忙嗎?

謝謝。 代碼:

public class JavaPasswordCount { 
    public JavaPasswordCount() { 
     JFrame window = new JFrame("Password Character Count"); 
     window.setSize(50, 50); 
     JButton bt1 = new JButton("Show Count"); 
     JButton bt2 = new JButton("Show Password"); 
     final JPasswordField pwd = new JPasswordField(); 
     final JTextField tf = new JTextField(); 
     final int counter; 

     JPanel panel = new JPanel(); 

     bt1.addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 
       tf.setText(pwd.getPassword()); 
      } 
     }); 

     bt2.addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 
       counter = pwd.length(); 
       tf.setText(counter); 
      } 
     }); 

     panel.setLayout(new FlowLayout()); // Add buttons and TextField to the panel 
     panel.add(tf); 
     panel.add(pwd); 
     panel.add(bt1); 
     panel.add(bt2); 

     window.getContentPane().add(panel, BorderLayout.CENTER); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.pack(); 
     window.setVisible(true); 
    } 
    public static void main(String[] args) { 
     try { 
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
     } catch (Exception e) { 
     } 

     JavaPasswordCount application = new JavaPasswordCount(); 
    } 
} 

回答

2

更改此行:

counter = pwd.length(); 
tf.setText(counter); 

int counter = pwd.getPassword().length; 
tf.setText(String.valueOf((counter))); 

tf.setText(pwd.getPassword()); 

tf.setText(pwd.getPassword().toString()); 
+0

Thanks @MrD。但是我仍然得到同樣的錯誤 - 當我想要讀取實際的密碼時,它停在「bt1」下的部分。 –

+0

很好,@MrD。謝謝你的幫助。公認。 –

+0

沒問題的隊友。記得要檢查一下:) –