views:

764

answers:

3

I would like to add a hint value to my JTextField. It should look like Firefox rendering of <input type="text" title="bla">. This creates a edit field with the text 'bla' in the background. If the textbox has focus the title-text disappeares and just reappears if the user leaves the editbox without text.

Is there a (free) swing component that does something like this?

+2  A: 

For any Swing component (that is, anything that extends JComponent), you can call the setToolTipText(String) method.

For more information, reference the following links:

Matt
I think he is not talking about tooltip, he wants something like "Type here to search" grey text which disappears when one starts typing
Dmitry
Hmm, you might be right, but that fit with the HTML he provided. OP.. if you're looking to clear/set default text when the input is focused/blurred, look into FocusListener: http://java.sun.com/docs/books/tutorial/uiswing/events/focuslistener.html
Matt
Dmitry is right. Thanks for your help.
Wienczny
+4  A: 

Take a look at this one: http://code.google.com/p/xswingx/

It is not very difficult to implement it by yourself, btw. A couple of listeners and custom renderer and voila.

Dmitry
+3  A: 

You could create your own:

import java.awt.BorderLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;

public class Main {   
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        frame.add(new HintTextField("A hint here..."), BorderLayout.NORTH);
        frame.add(new HintTextField("Another hint here..."), BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.pack();
    }
}

class HintTextField extends JTextField implements FocusListener {

    private final String hint;

    public HintTextField(final String hint) {
        super(hint);
        this.hint = hint;
        super.addFocusListener(this);
    }

    @Override
    public void focusGained(FocusEvent e) {
        if(this.getText().isEmpty()) {
            super.setText("");
        }
    }
    @Override
    public void focusLost(FocusEvent e) {
        if(this.getText().isEmpty()) {
            super.setText(hint);
        }
    }

    @Override
    public String getText() {
        String typed = super.getText();
        return typed.equals(hint) ? "" : typed;
    }
}

If you're still on Java 1.5, replace the this.getText().isEmpty() with this.getText().length() == 0.

Bart Kiers
This solution is nice, too. You would have to overload getText() and filter the hint-text.
Wienczny
Yes, absolutely.
Bart Kiers