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.
解决方案
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.