0

What I'm trying to do.

I'm basically trying to add a search bar to my program, made out of a JTextArea.

What I would like to do, is add an "example" into the search bar (greyed out text, which disapears when the JTextArea is activated). I've attempted this by changing the text colour, and adding a mouseListener to setText("");. However, this means that every time I click on the bar, it empties, which isn't something I want. (Say I typed in a really long string and had to retype it because it was 1 character wrong).

JTextField searchBar = new JTextField("Search...");
searchBar.setForeground("Color.GRAY");


searchBar.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                searchBar.setForeground(Color.BLACK);
                searchBar.setText("");
            }
}

What I'd like to know

How can I make it so that, each time the frame is repainted, the search bar will display search... in grey, until clicked, after which it remains persistent.

I hope it's clear why I'm trying to do, any help is appreciated.

Thanks.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • Use the [JTextField](https://docs.oracle.com/javase/8/docs/api/javax/swing/JTextField.html) `setSelectionStart` and `setSelectionEnd` methods to set the example text as a selection. Once a user types in the `JTextField`, don't erase the text. – Gilbert Le Blanc Jul 23 '22 at 12:18
  • *and adding a mouseListener* - and what if the user tabs to the text field? A GUI should always be designed to support mouse or keyboard interaction with the user. *the search bar will display search... in grey, until clicked* - check out [Text Prompt](https://tips4java.wordpress.com/2009/11/29/text-prompt/) which will allow you to customize the way the prompt is displayed until text is actually typed. – camickr Jul 23 '22 at 13:56

0 Answers0