Java JTextField Select selectAllOnFocus(final JTextField jtf, final String recoverText, final Color forTip, final Color forContent)

Here you can find the source of selectAllOnFocus(final JTextField jtf, final String recoverText, final Color forTip, final Color forContent)

Description

select All On Focus

License

LGPL

Declaration

public static void selectAllOnFocus(final JTextField jtf, final String recoverText, final Color forTip,
        final Color forContent) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.awt.Color;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTextField;

public class Main {

    public static void selectAllOnFocus(final JTextField jtf, final String recoverText, final Color forTip,
            final Color forContent) {
        jtf.addFocusListener(new FocusListener() {
            @Override//from  ww w. ja v  a2  s  . c  om
            public void focusLost(FocusEvent e) {
                if (recoverText != null) {
                    String text = jtf.getText();
                    if (text.isEmpty()) {
                        jtf.setForeground(forTip);
                        jtf.setText(recoverText);
                    } else if (text.equals(recoverText)) {
                        jtf.setForeground(forTip);
                    }
                }
            }

            @Override
            public void focusGained(FocusEvent e) {
                jtf.selectAll();
                jtf.setForeground(forContent);
            }
        });
        jtf.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2 && recoverText != null
                        && jtf.getText().equals(recoverText)) {
                    jtf.setText("");
                }
            }
        });
    }
}

Related

  1. buttonFolderSelect(final JTextField text)
  2. createSelected(final JTextField textField, final JButton... btns)
  3. focusAndSelectTextInTextField(JTextField textField)
  4. newFileChooser(String dialogTitle, int fileSelectionMode, JTextField textField, String globalLocation)
  5. recipientHintSelected(String hintString, JTextField toList, boolean shiftKeyPressed)
  6. selectByTyping(javax.swing.JTree tree, javax.swing.JTextField textfield)
  7. wrapWithFileChooser(final Component aParent, final JTextField aTextField, final int aFileSelectionMode)