2013-10-27 65 views
1

我在我的文本框上设置了默认文本,当用户将焦点放在文本框上时,程序如何删除此文本。副Versa,当用户不关注文本字段时,默认文本会回来。Java文本字段隐藏

我在考虑在TF上添加一个动作事件,但只有在用户点击了输入按钮的同时集中在TF上时才起作用。一个线程会工作吗?

回答

3

考虑将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 
    } 
}); 
+0

添加一些其他事件谢谢你的两个答案。这一个帮助我最多,终于学会了如何做到这一点,再次感谢两国人民:) – Arc

0

你可以叫你的任何JTextFields将这些功能

public void FocusGainedEmptyBox(JTextField txt) 
{ 
    txt.setText(null); 
} 

public void FocusLostFillBox(JTextField txt) 
{ 
    if(!txt.getText().equals("")) 
    { 
    txt.setText("I am Back"); 
    } 
} 

呼叫FocusGainedEmptyBox(txtValue)对分众和后获得了在聚焦丢失FocusLostFillBox(txtValue)。

0

如果您需要在文本字段上使用DocumentListener来了解文本何时更改,那么向文本字段中添加/删除文本可能会导致问题。

有关此问题的其他解决方案,请查看Text Prompt

0

我觉得你想要做一样像HTML占位符,

private void txtSearchStandardFocusLost(java.awt.event.FocusEvent evt) {            
     // TODO add your handling code here: 
     if (txtSearchStandard.getText().equals("")) { 
      txtSearchStandard.setText(" Type Here to Search Standard"); 
      txtSearchStandard.setForeground(Color.GRAY); 
     } 

    }           

    private void txtSearchStandardFocusGained(java.awt.event.FocusEvent evt) {            
     // TODO add your handling code here: 
     if (txtSearchStandard.getText().equals(" Type Here to Search Standard")) { 
      txtSearchStandard.setText(""); 
     } 

     txtSearchStandard.setForeground(Color.BLACK); 
    } 

但请记住这个当你试图在这个相同的文本框