如何在点击外部时将文本设置为JTextField?

时间:2017-05-16 15:39:34

标签: java listener jtextfield

当我从组件中单击时,如何将文本设置为JTextField? 每当我点击它时,它都会清除这样的文字:

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

但是,当我点击文本字段时,如何重置它? 我尝试了FocusEvent,但它没有按照我的意愿工作。

1 个答案:

答案 0 :(得分:1)

我认为您只需要将一个FocusListener添加到textField。这里有一个我写的课程,你可以按照自己的意愿工作。

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

}