[英]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 like," Please enter your phone number", and then have that disappear so the the user doesn't have to delete the text?
即使没有突出显示,您如何也可以使用“请输入您的电话号码”之类的字段来进行初始化,然后使该字段消失,从而使用户不必删除文本?
JTextFiled
instance with some known text like "Please enter your phone number" JTextFiled
实例。 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) {
}
});
There is another approach, with the focusGained event. 还有另外一种方法,带有focusGained事件。 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. 这样,无论何时用户在jTextArea1中键入内容,初始文本都将立即被替换。
and in focusLost
it's good usability to put the initial text back if the user did not input anything. 并且在
focusLost
,如果用户未输入任何内容,则可以放回初始文本,这是很好的可用性。 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. 或者,如果你不想使用
focusLost
方法,你可以创建一个内部类MyFocusListener
扩展FocusAdapter
,这样你只需要实现您要使用的方法。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.