-2

I am relatively new with Java programming, and I wrote some code that places a JLabel, with the text set to "Enter text here" behind a JTextField. (Similar to the way the Microsoft Sign-in page functions) I would like to know if there is a way to delete the text of the JLabel when the user begins typing in the text field. (Or if such an event handler even exists.)

Any help would be much appreciated.

ghipkins
  • 73
  • 1
  • 10
  • try it http://stackoverflow.com/questions/5443682/how-add-a-listener-for-jtexfield-when-it-changing – Marco Acierno Jun 03 '14 at 14:57
  • Typing "java jtextfield onchange" into Google produced a nice list of dupe questions with answers. Here's another one: http://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield – Gimby Jun 03 '14 at 14:58
  • I think you want an ActionListener... – Anubian Noob Jun 03 '14 at 14:59
  • What you want is a [TextPrompt](http://tips4java.wordpress.com/2009/11/29/text-prompt/)-like component or [PromptSupport](https://weblogs.java.net/blog/kschaefe/archive/2010/07/15/swingx-using-promptsupport)-from SwingX – Paul Samsotha Jun 03 '14 at 15:01

2 Answers2

2

for some specific fields backed by a Document you can have a document change listener as shown here:

Value Change Listener to JTextField

Community
  • 1
  • 1
Lorenzo Boccaccia
  • 6,041
  • 2
  • 19
  • 29
0

There is no generic onChange function. However there is a method you can define in a class that implements KeyListener which is public void keyPress. You would use this something like the following:

public class MyClass implements KeyListener {

    private JTextField myField;
    private JLabel myLabel;

    public MyClass() {
        myLabel = new JLabel("Enter text here");
        myField = new JTextField();
        myField.addKeyListener(this);
    }

    @Override
    public void keyPress(KeyEvent e) {
        myLabel.setText("");
    }
}

There is of course a lot more flexibility you can add to this, but the above is the general idea. For example, you could make sure that the KeyEvent is coming from the appropriate source, as rightly you should:

@Override
public void keyPress(KeyEvent e) {
    if(e.getSource() == myField) {
        myLabel.setText(""):
    }
}

... and lots of other stuff. Have a look at Oracle's Event Listener tutorials.

asteri
  • 11,402
  • 13
  • 60
  • 84
  • This won't work. First off, `addActionListener(this)` requires your class to implement `ActionListener`, not `KeyListener`. Second, you would be better off implementing `FocusListener` for this problem. – Nathaniel Jones Jun 03 '14 at 15:11
  • @NathanielJones You're right, it should be `addKeyListener`. My mistake, typing this up at work, haha. And you're wrong about the `FocusListener`, since the OP explicitly says `I would like to know if there is a way to set the text to "" when the user starts typing in the text field`. W – asteri Jun 03 '14 at 15:29