Dies ist eine alte Version des Dokuments!


Java - AWT/Swing

JTextField, mit grauem Hinseitext

Möchte man ein Textfield mit grauem Hinseistext, welcher beim Anklciekn verschwindet, so hilft dieser Code:
Dazu wird ein eigenes Document „MaxSizeDocument“ definiert.


public class PromptTextField extends JTextField {
   private String promptText;
 
   public PromptTextField(String promptText) {
      super(promptText);
      this.promptText = promptText;
      addFocusListener(new FocusListener() {
         public void focusGained(FocusEvent e) {
            PromptTextField.this.setForeground(Color.BLACK);
            if (PromptTextField.this.getText() != null && PromptTextField.this.getText().equals(promptText))
               PromptTextField.this.setText("");
         }
 
         public void focusLost(FocusEvent e) {
            if (PromptTextField.this.getText() == null || PromptTextField.this.getText().trim().length() == 0)
               PromptTextField.this.setText(promptText);
            if (PromptTextField.this.getText().equals(promptText)) {
               PromptTextField.this.setForeground(Color.LIGHT_GRAY);
            }
         }
      });
   }
}


Eine Verwendung sähe so aus:

JTextField tfExample = new PromptTextField("Bitte was eingeben!");
add(tfExample, BorderLayout.NORTH);



Stichworte:

JTextField, mit Hinsweistext, grau, Prompt

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007