[英]How to add actionlistener to textfield in Java
因此,這就是概念:簡單來說,有一個文本框,其名稱為“名稱”,我希望如果在文本框中的任意位置單擊,則值“名稱”將消失。 這是我在代碼中所做的:
JTextField t1 = new JTextField("Name", 10);
t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent cl){
t1.setText(" ");
}
});
沒有語法錯誤,但是當我運行該程序並在文本框中單擊某個位置時,什么也沒有發生,並且值“ Name”仍然存在
任何幫助將不勝感激,謝謝!
您可以嘗試以下方法:
t1.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
t1.setText(null); // Empty the text field when it receives focus
}
});
為此,您不應該使用ActionListener。 相反,FocusListener應該適合您,請在此處進行說明: http : //www.java2s.com/Code/JavaAPI/javax.swing/JTextFieldaddFocusListenerFocusListenerl.htm
不要使用ActionListener,它不是在實現您需要的類。 您還可以通過以下方式添加MouseListener:
t1.addMouseListener(new MouseListener(){...});
http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.