JTextField 預設文字提示功能
阿新 • • 發佈:2019-01-06
當JTextField沒有輸入時,顯示提示文字,類似於
通過實現FocusListener來實現。
然後直接使用JTextField呼叫即可import java.awt.Color; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.JTextField; public class JTextFieldHintListener implements FocusListener { private String hintText; private JTextField textField; public JTextFieldHintListener(JTextField jTextField,String hintText) { this.textField = jTextField; this.hintText = hintText; jTextField.setText(hintText); //預設直接顯示 jTextField.setForeground(Color.GRAY); } @Override public void focusGained(FocusEvent e) { //獲取焦點時,清空提示內容 String temp = textField.getText(); if(temp.equals(hintText)) { textField.setText(""); textField.setForeground(Color.BLACK); } } @Override public void focusLost(FocusEvent e) { //失去焦點時,沒有輸入內容,顯示提示內容 String temp = textField.getText(); if(temp.equals("")) { textField.setForeground(Color.GRAY); textField.setText(hintText); } } }
JTextField jTextField = new JTextField();
jTextField.addFocusListener(new JTextFieldHintListener(jTextField, "提示內容"));