JTextField focus question
Was wondering if it is possible to initialize a text field with printing (this part I know how to do), but then have the printing highlighted, and then disappear when the user starts typing? Even without the highlighting, how can you have the field initialize with something li开发者_StackOverflow中文版ke," Please enter your phone number", and then have that disappear so the the user doesn't have to delete the text?
There is another approach, with the focusGained event. Just mark the initial Text:
String initialText = "Enter your story here...";
...
jTextArea1.setText(initialText);
...
private void focusGained(java.awt.event.FocusEvent evt) {
if (jTextArea1.getText().equals(initialText)) {
//jTextArea1.setSelectionStart(0);
//jTextArea1.setSelectionEnd(jTextArea1.getText().length());
jTextArea1.selectAll();
}
}
This way whenever the user types something in the jTextArea1 the initial text will be substituted immediately.
- Initialize the
JTextFiled
instance with some known text like "Please enter your phone number" - Implement FocusListener
- In focusGained() check the JTextField instance to see if it has the known text and if it does clear the text; if not, do nothing.
Here's a code sample
final String INITIAL_TEXT = "Please enter your ph. number";
final JTextField textField = new JTextField(INITIAL_TEXT);
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if (textField.getText().equals(INITIAL_TEXT)) {
textField.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
}
});
and in focusLost
it's good usability to put the initial text back if the user did not input anything. Like so:
public void focusLost(FocusEvent e)
{
// If the field is empty, set the default text when losing focus.
if (inputField.getText().isEmpty())
{
inputField.setText(INITIAL_TEXT);
}
}
Or, if you don't want to use the focusLost
method, you can create an inner class MyFocusListener
that extends FocusAdapter
, that way you only need to implement the methods you intend to use.
private class MyFocusListener extends FocusAdapter
{
public void focusGained(FocusEvent e)
{
// do your magic!
}
// ignore the focusLost method
}
public boolean isCorrect() {
data = new String[6];
for (int i = 0; i < informationLabel.length; i++) {
if (i == 0) {
if (!informationTextField[i].getText().equals("")) {
data[i] = informationTextField[i].getText();
}
else
return false;
}
if (i == 1 || i == 2) {
if (informationPasswordField[i - 1].getText().equals(""))
return false;
}
if (i == 3 || i == 4 || i == 5 || i == 6) {
if (!informationTextField[i - 2].getText().equals("")) {
data[i - 1] = informationTextField[i - 2].getText();
}
else
return false;
}
}
return true;
}
精彩评论