简体   繁体   中英

How to setText to JTextField when clicking outside of it?

How can I set text to JTextField when I click off from the component? Whenever I click it, it will clear the text like this:

// Clears the "Enter text here..." when clicked
    commandLine.addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
            commandLine.setText("");
        }
    });  

But, when I click off the textfield, how can I reset it? I tried FocusEvent but it did not work as I wanted.

I think you just need to add a FocusListener to the textField. Here there is a class I've written that works as you want.

class CustomPlaceholderTextField extends JTextField implements FocusListener {

private static final long serialVersionUID = 1L;
private boolean changedText = false;
private final String placeholder;


public CustomPlaceholderTextField(String placeholder){
    super();
    this.placeholder = Objects.requireNonNull(placeholder);
    this.addFocusListener(this);
    super.setText(placeholder);

}

@Override
public String getText() {
    if (this.changedText) {
        return super.getText();
    } else {
        return "";
    }
}

@Override
public void setText(String t) {
    if (t == null || t.isEmpty()) {
        super.setText(this.placeholder);
        this.changedText = false;
    } else {
        super.setText(t);
        this.changedText = true;
    }
}

@Override
public void focusGained(FocusEvent e) {
    if (!this.changedText) {
        super.setText("");
        this.changedText = true;
    }
}

@Override
public void focusLost(FocusEvent e) {
    if (this.getText().isEmpty()) {
        super.setText(this.placeholder);
        this.changedText = false;
    } else {
        this.changedText = true;
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM