Example text in JTextField

后端 未结 7 2062
独厮守ぢ
独厮守ぢ 2021-01-18 05:15

I am looking for a way to put example text into a swing JTextField and have it grayed out. The example text should then disappear as soon as any thing is entered into that t

相关标签:
7条回答
  • 2021-01-18 05:48

    Do it like this:

    1. Define the string with the initial text you like and set up your TextField:

      String initialText = "Enter your initial text here";
      jTextField1.setText(initialText);
      
    2. Add a Focus Listener to your TextField, which selects the entire contents of the TextField if it still has the initial value. Anything you may type in will replace the entire contents, since it is selected.

      jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
          public void focusGained(java.awt.event.FocusEvent evt) {
             if (jTextField1.getText().equals(initialText)) {
                jTextField1.selectAll();
             }
          }
      });
      
    0 讨论(0)
提交回复
热议问题