[英]JButton enabled when two textfields are equal
當同一面板中的兩個文本字段相等時,我無法啟用JButton
。 我嘗試添加一個ActionListener
但仍然沒有發生任何事情,並且我的JButton
保持禁用狀態。 當我簡單地嘗試str1.contentEquals(str2)
時,同樣的事情發生了。
txtPassword = new JTextField();
txtPassword.setForeground(Color.LIGHT_GRAY);
txtPassword.setText("password");
txtPassword.setBounds(115, 49, 200, 20);
panel.add(txtPassword);
txtPassword.setColumns(10);
String str1 = txtPassword.getText();
txtRepeatPassword = new JTextField();
txtRepeatPassword.setForeground(Color.LIGHT_GRAY);
txtRepeatPassword.setText("repeat password");
txtRepeatPassword.setBounds(115, 124, 200, 20);
panel.add(txtRepeatPassword);
txtRepeatPassword.setColumns(10);
String str2 = txtRepeatPassword.getText();
JButton btnNewButton = new JButton("Next >>>");
btnNewButton.setVisible(true);
btnNewButton.setEnabled(false);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panelPYT.setVisible(true);
panel.setVisible(false);
}
});
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnNewButton.setBounds(88, 182, 259, 50);
panel.add(btnNewButton);
txtPassword.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
same();
}
public void removeUpdate(DocumentEvent e) {
same();
}
public void insertUpdate(DocumentEvent e) {
same();
}
public void same() {
if (str1.equals(str2)){
btnNewButton.setEnabled(true);
}
else {
btnNewButton.setEnabled(false);
}
}
});
JButton btnNext = new JButton("Next >>>");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPYT.setVisible(false);
panel.setVisible(true);
}
});
您正在將偵聽器添加到txtPassword
,但我假設用戶首先將密碼輸入txtPassword
,然后再輸入txtRepeatPassword
。 這意味着當用戶在第一個字段中完成輸入時, DocumentListener
完成觸發,當他們在第二個字段中輸入密碼時,偵聽器不會觸發,因為輸入發生在txtRepeatPassword
中。
長話短說,只需將DocumentListener
添加到兩個文本字段。
DocumentListener dlist = new DocumentListener(){
.... all your methods
};
txtPassword.getDocument().addDocumentListener(dlist);
txtRepeatPassword.getDocument().addDocumentListener(dlist);
你也需要改變
if (str1.equals(str2)){
btnNewButton.setEnabled(true);
}else {
btnNewButton.setEnabled(false);
}
至
if (txtPassword.getText().equals(txtRepeatPassword.getText())){
btnNewButton.setEnabled(true);
}else {
btnNewButton.setEnabled(false);
}
按照您的方式, str1
和str2
只是在初始化時保存各自文本框的值。 您想比較它們在偵聽器觸發時所持有的值,因此您必須在那時檢索該值。
如果(str1.equals(str2)){
字符串的值不會因為您在文本字段中鍵入而改變。
每次檢查時都需要從文本字段中獲取文本:
String str1 = textPassword.getText();
String str2 = textRepeatPassword.getText();
if (str1.equals(str2)){
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.