You can control whether the contents of a text field may be modified by the user by
calling setEditable( ). You can determine editability by calling isEditable( ). These methods
are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not. In setEditable( ), if
canEdit is true, the text may be changed. If it is false, the text cannot be altered.
There may be times when you will want the user to enter text that is not displayed, such
as a password. You can disable the echoing of the characters as they are typed by calling
setEchoChar( ). This method specifies a single character that the TextField will display when
characters are entered (thus, the actual characters typed will not be shown). You can check a
text field to see if it is in this mode with the echoCharIsSet( ) method. You can retrieve the
echo character by calling the getEchoChar( ) method. These methods are as follows:
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Here, ch specifies the character to be echoed.
Handling a TextField
Since text fields perform their own editing functions, your program generally will not
respond to individual key events that occur within a text field. However, you may want
to respond when the user presses ENTER. When this occurs, an action event is generated.
Here is an example that creates the classic user name and password screen:
// Demonstrate text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet
implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home