Search code examples
javalistenerjtextfield

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.


Solution

  • 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;
        }
    }
    

    }