我在我的文本字段上设置了默认文本,当用户关注文本字段时,程序如何删除该文本。反之亦然,当用户不关注文本字段时,默认文本会返回。
我正在考虑在 TF 上添加一个 Action 事件,但只有当用户在关注 TF 时点击回车按钮时才有效。线程会起作用吗?
最佳答案
考虑将 FocusListener 添加到 JTextField。在 focusGained(FocusEvent e)
方法中,您可以检查 JTextField 的文本,如果它与预览文本完全匹配,则将其删除。在 focusLost(FocusEvent e)
方法中,您检查 JTextField 是否为空,如果是,则重新添加默认文本。
myTextField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e){
// get text from JTextField
// if text matches default text, either select all, so user can keep it or change it
// or delete it --- your choice
}
public void foucsLost(FocusEvent e){
// check if JTextField's text is empty.
// if so, cal setText(DEFAULT_TEXT) on the field
}
});
关于Java 文本字段聚焦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618134/