Article View: borland.public.jbuilder.java.swing
Article #13192Re: Prevent further input once x # of chars entered into a JTextField
From: Vladimir Olenin
Date: Sun, 30 Aug 1998 00:00
Date: Sun, 30 Aug 1998 00:00
875 lines
32691 bytes
32691 bytes
This is a multi-part message in MIME format.
--------------B2865773E58F282F8BE3297C
Content-Type: text/plain; charset=koi8-r
Content-Transfer-Encoding: 7bit
Hi, david,
Actually u should read through Swing tutorial at javasoft site. There is
the exact thing u're looking for. In case u haven't much time, i
attached this page to this message.
Vladimir
David Jensen wrote:
>
> How can I prevent further input once x # of characters have been entered
> into either a JTextField or a JTextArea control? I know that the answer
> lies somewhere in tweaking either control's document model, but I'm not sure
> what method to call, or when.
>
> Does anybody have any ideas, suggestions, or code samples on this one? Any
> assistance would be greatly appreciated.
>
> Thanks in advance,
> David Jensen
> <jensend@txen.com>
--------------B2865773E58F282F8BE3297C
Content-Type: text/html; charset=koi8-r;
name="textfield.html"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="textfield.html"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<!--NewPage-->
<html>
<head>
<title>How to Use Text Fields</title>
</head>
<body BGCOLOR="#ffffff">
<table width="100%">
<tr>
<td align=left>
<a href="text.html"><img src="../../images/PreviousArrow.gif" width=26 height=26 align=bottom border=0 alt="Previous | "></a><a
href="toolbar.html"><img src="../../images/NextArrow.gif" width=26 height=26 align=bottom border=0 alt="Next | "></a><a
href="../../trailmap.html"><img src="../../images/WayUpArrow.gif" width=26 height=26 align=bottom border=0 alt="Trail Map | "></a><a
href="../index.html"><img src="../../images/uiHeader.gif" width=26 height=26 align=bottom border=0 alt="Creating a User Interface | "></a>
</td>
<td align=right>
<a href="index.html"><strong><em>Using the JFC/Swing Packages</em></strong></a>
</td>
</tr>
</table>
<p>
<center>
<IMG SRC="../../images/shoeline2.GIF" ALIGN="BOTTOM" BORDER="0" WIDTH="202"
HEIGHT="25" NATURALSIZEFLAG="3">
<IMG SRC="../../images/shoeline2.GIF" ALIGN="BOTTOM" BORDER="0" WIDTH="202"
HEIGHT="25" NATURALSIZEFLAG="3">
</center>
<p>
<h2>
How to Use Text Fields
</h2>
<p>
<blockquote>
Text fields display a single line of selectable,
optionally editable text.
Generally you use the
<a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.JTextField.html"><code>JTextField</code></a><a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.JTextField.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a> class to provide text fields.
If you need to provide a <em>password field</em> --
an editable text field that doesn't show
the characters the user types --
use the
<a href="#password"><code>JPasswordField</code></a>
class instead.
This section discusses both text fields and password fields.
<p>
If you want a text field that also provides a menu of strings
to choose from, consider using an editable
<a href="combobox.html">combo box</a>.
If you need to obtain more than one line of input from the user,
then you should use one of the classes that implements
a general-purpose <a href="text.html">text area</a>.
<p>
The applet pictured below is the Swing version of
an AWT example program described in
<a target="_top" href="../components/text.html">How to Use TextAreas and TextFields</a><a target="_top" href="../components/text.html"><img src="../../images/uiIcon.gif" width=20 height=20 border=0 alt="(in the Creating a User Interface trail)"></a>.
<blockquote><IMG SRC="../../figures/ui/TextDemoSwing.gif" WIDTH="261" HEIGHT="206" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT=""></blockquote>
[PENDING: in the figure put a callout to the field and the area]
<p>
The applet displays a basic text field and a text area.
The text field is editable; the text area isn't.
When the user presses Return
in the text field,
the field fires an
<a target="_top" href="../components/actionlistener.html">action event</a><a target="_top" href="../components/actionlistener.html"><img src="../../images/uiIcon.gif" width=20 height=20 border=0 alt="(in the Creating a User Interface trail)"></a>.
The applet reacts to the event by copying the text field's
contents to the text area,
and then selecting all the text in the text field.
<p>
You can find the source for the program in
<a href="example-swing/TextDemo.java"><code>TextDemo.java</code></a>.
The corresponding HTML file,
<a href="example-swing/TextDemo.html"><code>TextDemo.html</code></a>,
contains an <code><APPLET></code> tag for running the applet.
[PENDING: should use OBJECT/EMBED tags, too,
so this will work with Plug-in.]
Here's the code from <code>TextDemo</code>
that creates the text field in the applet:
<blockquote>
<pre>
textField = new JTextField(20);
...
getContentPane().add(textField);
...
textField.addActionListener(this);
</pre>
</blockquote>
The <code>JTextField</code> constructor
takes an integer parameter indicating the desired number of
columns in the text field.
The next lines of code add the text field to the applet's content
pane, and then register the applet as an action listener for
the text field.
Here's the <code>actionPerformed</code> method
that implements the applet's action event handling:
<blockquote>
<pre>
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text + newline);
textField.selectAll();
}
</pre>
</blockquote>
This example illustrates using a basic,
off-the-shelf text field for entering textual data
and performing some task when the text field
fires an action event.
This is sufficient for many programs.
Other programs, however, need more advanced behavior.
As a subclass of
<a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.text.JTextComponent.html"><code>JTextComponent</code></a><a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.text.JTextComponent.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a>, <code>JTextField</code> can be configured and customized.
One common customization is to provide a text field
whose contents is validated. This topic and others
are covered in the sections that follow:
<ul>
<li><a href="#validation">Creating a Validated Text Field</a>
<li><a href="#documentlistener">Using a Document Listener on a Text Field</a>
<li><a href="#layout">Laying Out Label/Text Field Pairs</a>
<li><a href="#password">Providing a Password Field</a>
<li><a href="#apitables">The Text Field API</a>
<li><a href="#examples">Examples that Use Text Fields</a>
</ul>
<a name="validation">
<h4>Creating a Validated Field</h4>
</a>
<blockquote>
Many programs require users to enter textual data of
a certain type or format.
For example, a program might provide a text field
for entering a date, a decimal number, or a phone number.
The contents of such a text field must be validated
before being used for any purpose.
A text field can be <em>action</em>-validated or <em>keystroke</em>-validated.
<p>
The data in an action-validated field is checked
each time the field fires an action event
(each time the user presses the return key).
An action-validated field might, at any given point in time,
contain invalid data.
However, the data is validated before it's used for anything.
To create an action-validated field,
provide an action listener for your field and implement
its <code>actionPerformed</code> method as follows:
<ul>
<li> Use <code>getText</code> to get the contents of the text field.
<li> Evaluate the value returned by <code>getText</code>.
<li> If the value is valid, do whatever task or calculation is required.
If the value is invalid, report an error and return without
performing a task or calculation.
</ul>
<p>
The data in a keystroke-validated field is checked
each time the field changes.
A field that is keystroke-validated can never contain invalid data
because every keystroke that causes the data to be invalid is rejected.
To create a keystroke-validated text field you need to
provide a custom document for your text field.
This section will show you how, but first,
a note to correct a common misconception.
<p>
<blockquote>
<hr>
<strong>Warning:</strong> Do not use a document for keystroke validation.
By the time a document listener has been notified of a change,
it's too late, the change has already taken place.
See <a href="text.html#doclistener">Listening for Changes on a Document</a>
for more information.
<hr>
</blockquote>
Now that you know what not to do,
let's look at an example of what to do.
<p>
To implement keystroke validation
you need to provide a custom document for your text component.
If you aren't familiar with documents yet,
see <a href="text.html#document">Working With a Text Component's Document</a>.
<p>
The application shown in the following figure
has four keystroke-validated text fields.
The user enters loan information
into the first three text fields.
Each time the user types a character,
the program validates the input and
updates the result in the fourth text field.
<blockquote><IMG SRC="../../figures/ui/TextFieldDemo.gif" WIDTH="277" HEIGHT="146" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT=""></blockquote>
<blockquote>
<hr>
<strong>Try this:</strong>
<ol>
<li> Compile and run the application.
The source file is
<a href="example-swing/TextFieldDemo.java"><code>TextFieldDemo.java</code></a>.
You will also need
<a href="example-swing/WholeNumberField.java"><code>
WholeNumberField.java</code></a>,
<a href="example-swing/DecimalField.java"><code>
DecimalField.java</code></a>, and
<a href="example-swing/FormattedDocument.java"><code>
FormattedDocument.java</code></a>.
<br>
See <a href="swingStart.html">Getting Started with Swing</a>
if you need help.
<li> Enter information into the text fields and see the results.
<br>
If attempt to you enter invalid data, the program beeps.
<li> Try to type into the fourth text field.
<br>
You can't because it isn't editable.
However, you can select the text.
<li> Resize the window.
<br>
Note how the labels and text fields remain aligned.
<a href="#layout">Laying Out Label/Text Field Pairs</a>
talks more about this feature of the program.
</ol>
<hr>
</blockquote>
The <strong>Years</code> field is an instance of
<a href="example-swing/WholeNumberField.java">
<code>WholeNumberField.java</code></a>,
which is a subclass of <code>JTextField</code>.
By overriding the <code>createDefaultModel</code> method,
<code>WholeNumberField</code> establishes a custom <code>Document</code>
subclass -- an instance of
<code>WholeNumberDocument</code> --
as the document for each <code>WholeNumberField</code> created:
<blockquote>
<pre>
protected Document createDefaultModel() {
return new WholeNumberDocument();
}
</pre>
</blockquote>
Here's the implementation of <code>WholeNumberDocument</code>:
<blockquote>
<pre>
protected class WholeNumberDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
char[] source = str.toCharArray();
char[] result = new char[source.length];
int j = 0;
for (int i = 0; i < result.length; i++) {
if (Character.isDigit(source[i]))
result[j++] = source[i];
else {
toolkit.beep();
System.err.println("insertString: " + source[i]);
}
}
super.insertString(offs, new String(result, 0, j), a);
}
}
</pre>
</blockquote>
This class overrides the <code>insertString</code> method
which is called every time any string or character
is about to be inserted into the document.
<code>WholeNumberDocument</code>'s implementation of
<code>insertString</code> evaluates
each character to be inserted into the text field.
If the character is a digit, the document allows it to be inserted.
Otherwise, the method beeps and prints an error message.
Thus <code>WholeNumberDocument</code> allows the numbers
in the range 0, 1, 2, ...
<p>
An interesting implementation detail
is that our custom document class does not have to override
the <code>remove</code> method.
The <code>remove</code> method is called each time
a character or group of characters is removed from the
text field.
Because removing a digit from an integer cannot produce an
invalid result, this class does not
pay attention to removals.
<p>
The other two input fields in the example,
as well as the uneditable <strong>Monthly Payment</code> field,
are all instances of
<a href="example-swing/DecimalField.java"><code>DecimalField.java</code></a>,
a custom <code>JTextField</code> subclass.
<code>DecimalField</code> uses a custom document,
<a href="example-swing/FormattedDocument.java">
<code>FormattedDocument</code></a>,
that allows only data of a particular format to be entered.
<p>
<code>FormattedDocument</code> has no knowledge
of the actual format of its content.
Instead, <code>FormattedDocument</code> relies on a formatter,
an instance of a subclass of
<a target="_top" href="http://java.sun.com/products/jdk/1.1/api/java.text.Format.html"><code>Format</code></a><a target="_top" href="http://java.sun.com/products/jdk/1.1/api/java.text.Format.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a>, to accept or reject a proposed change.
The text field that uses the <code>FormattedDocument</code>
must specify which formatter the <code>FormattedDocument</code> uses.
<p>
The <strong>Loan Amount</strong>
and <strong>Monthly Payment</strong> text fields
use a
<a target="_top" href="http://java.sun.com/products/jdk/1.1/api/java.text.NumberFormat.html"><code>NumberFormat</code></a><a target="_top" href="http://java.sun.com/products/jdk/1.1/api/java.text.NumberFormat.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a> object created like this:
<blockquote>
<pre>
moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);
((DecimalFormat)moneyFormat).setPositiveSuffix(" ");
</pre>
</blockquote>
The following code creates the <strong>APR</strong> text field's formatter:
<blockquote>
<pre>
percentFormat = NumberFormat.getPercentInstance(Locale.US);
percentFormat.setMinimumFractionDigits(3);
</pre>
</blockquote>
As the code shows, the same class (<code>NumberFormat</code>)
can support a currency format and a percentage
format. Furthermore, <code>Format</code> and its
subclasses are locale-sensitive, so decimal field can be
made to support formats for other countries and regions.
Refer to
<a target="_top" href="../../i18n/format/index.html">Formatting</a><a href="../../i18n/format/index.html"><img src="../../images/internatsm.GIF" width=20 height=20 border=0 alt="(in the Internationalization trail)"></a> in the internationalization trail
for detailed information about formatters.
<p>
Here is <code>FormattedDocument</code>'s implementation
of <code>insertString</code>:
<blockquote>
<pre>
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
String currentText = getText(0, getLength());
String beforeOffset = currentText.substring(0, offs);
String afterOffset = currentText.substring(offs, currentText.length());
String proposedResult = beforeOffset + str + afterOffset;
try {
formatter.parseObject(proposedResult);
super.insertString(offs, str, a);
} catch (ParseException e) {
Toolkit.getDefaultToolkit().beep();
System.err.println("insertString: could not parse: " + proposedResult);
}
}
</pre>
</blockquote>
The method uses the formatter to parse the result
of the proposed insertion.
If the result is properly formatted,
this method calls <code>super.insert</code>
to do the insertion. If the result is not properly
formatted, the computer beeps.
<p>
In addition to overriding <code>insertString</code>,
<code>FormattedDocument</code> also overrides the
<code>remove</code> method.
Recall that the <code>remove</code> method is called
each time a character or group of characters
is to be removed from the document.
<blockquote>
<pre>
public void remove(int offs, int len) throws BadLocationException {
String currentText = getText(0, getLength());
String beforeOffset = currentText.substring(0, offs);
String afterOffset = currentText.substring(len + offs, currentText.length());
String proposedResult = beforeOffset + afterOffset;
try {
if (proposedResult.length() != 0)
formatter.parseObject(proposedResult);
super.remove(offs, len);
} catch (ParseException e) {
Toolkit.getDefaultToolkit().beep();
System.err.println("remove: could not parse: " + proposedResult);
}
}
</pre>
</blockquote>
The <code>DocumentFormatter</code> implementation of
the <code>remove</code> method
is similar to its implementation of the <code>insertString</code> method.
method. The formatter parses the result
of the proposed change
and performs the removal or not,
depending on whether the result is valid.
</blockquote>
<a name="documentlistener">
<h4>Using a Document Listener on a Text Field</h4>
</a>
<blockquote>
So, if you can't use a document listener
for field validation, what can you use it for?
Use it to listen to, but not interfere with,
changes to the document's content.
The loan calculator uses the following document listener
to update the monthly payment after every change:
<blockquote>
<pre>
class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
update(e);
}
public void removeUpdate(DocumentEvent e) {
update(e);
}
public void changedUpdate(DocumentEvent e) {
// we won't ever get this with a PlainDocument
}
private void update(DocumentEvent e) {
Document whatsup = e.getDocument();
if (whatsup.getProperty("name").equals("amount"))
amount = amountField.getValue();
else if (whatsup.getProperty("name").equals("rate"))
rate = rateField.getValue();
else if (whatsup.getProperty("name").equals("numPeriods"))
numPeriods = numPeriodsField.getValue();
payment = computePayment(amount, rate, numPeriods);
paymentField.setValue(payment);
}
}
</pre>
</blockquote>
This is an appropriate use of a document listener.
<p>
For general information about document listeners refer to
<a href="text.html#doclistener">Listening for Changes on a Document</a>.
</blockquote>
<a name="layout">
<h4>Laying Out Label/Text Field Pairs</h4>
<blockquote>
Rows of label and text field pairs such as those found in the loan calculator
are quite common on preference panels and panels that implement forms.
Here's the code that lays out the lable and text field pairs.
<blockquote>
<pre>
. . .
//Layout the labels in a panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new GridLayout(0, 1));
labelPane.add(amountLabel);
labelPane.add(rateLabel);
labelPane.add(numPeriodsLabel);
labelPane.add(paymentLabel);
//Layout the text fields in a panel
JPanel fieldPane = new JPanel();
fieldPane.setLayout(new GridLayout(0, 1));
fieldPane.add(amountField);
fieldPane.add(rateField);
fieldPane.add(numPeriodsField);
fieldPane.add(paymentField);
//Put the panels in another panel, labels on left,
//text fields on right
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
contentPane.setLayout(new BorderLayout());
contentPane.add(labelPane);
contentPane.add(fieldPane, "East");
setContentPane(contentPane);
. . .
</pre>
</blockquote>
You may be surprised to find
that the labels are laid out without reference to the text fields
and, in fact, are in a different panel,
yet align correctly with them.
This is a side effect of the layout managers
used by the program.
<blockquote><IMG SRC="../../figures/ui/TextFieldDemoWithLayout.gif" WIDTH="278" HEIGHT="201" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT=""></blockquote>
As the diagram illustrates,
the program uses two <code>GridLayout</code> managers,
one to lay out the column of labels and one for the column of text fields.
<code>GridLayout</code> guarantees that all of its components
are the same size, so all of the text fields are the same
height and all of the labels are the same height.
<p>
To get the labels and the text fields to align,
the program uses a third layout manager, a <code>BorderLayout</code>.
With just two components at East and Center,
<code>BorderLayout</code> guarantees the columns are the same height.
Thus, the labels and the text fields align.
<p>
Another way to get labels and text fields to align
is to use the AWT's most flexible, complex layout manager:
<a target="_top" href="../layout/gridbag.html"><code>GridBagLayout</code></a><a target="_top" href="../layout/gridbag.html"><img src="../../images/uiIcon.gif" width=20 height=20 border=0 alt="(in the Creating a User Interface trail)"></a>.
</blockquote>
<a name="password">
<h4>Providing a Password Field</h4>
</a>
<blockquote>
Swing provides the
<a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.JPasswordField.html"><code>JPasswordField</code></a><a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.JPasswordField.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a> class, a subclass of <code>JTextField</code>,
to use in place of a text field when the text entered by
a user is a password.
For security reasons,
a password field doesn't show the characters the user types.
Instead the field displays another character
such as an asterisk '*'.
<p>
The <a href="example-swing/PasswordDemo.java"><code>
PasswordDemo</code></a> example
described in
<a href="threads.html#SwingWorker">Using the SwingWorker Class</a>
uses a <code>JPasswordField</code>.
The program brings up a small window to prompt the
user to type in a password:
<blockquote><IMG SRC="../../figures/ui/PasswordDemo.gif" WIDTH="290" HEIGHT="89" ALIGN="BOTTOM" NATURALSIZEFLAG="3" ALT=""></blockquote>
Here's the code from <code>PasswordDemo</code> that creates
and sets up the password field.
<blockquote>
<pre>
JPasswordField password = new JPasswordField(10);
password.setEchoChar('#');
password.addActionListener(showSwingWorkerDialog);
</pre>
</blockquote>
The argument passed into the <code>JPasswordField</code> constructor
indicates that the field should be 10 columns wide.
By default a password field displays an asterisk '*' for
each character typed. The call to <code>setEchoChar</code>
changes it to a pound sign '#'.
Finally, the code adds an action listener to the password field.
The action listener's <code>actionPerformed</code> method
gets the password typed by the user and verifies it with
this code:
<blockquote>
<pre>
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField)e.getSource();
char[] password = input.getPassword();
if (isPasswordCorrect(password))
JOptionPane.showMessageDialog(f, worker.get());
else
JOptionPane.showMessageDialog(f,
new JLabel("Invalid password."));
}
</pre>
</blockquote>
This method uses the password field's <code>getPassword</code>
method to get the contents of the field.
The <code>isPasswordCorrect</code> method compares
the value entered by the user with the correct password.
<p>
<blockquote>
<hr>
<strong>Note</strong>: The <code>getPassword</code> method
and its companion setter, <code>setPassword</code>,
did not exist in Swing 1.0.3 and earlier releases.
<hr>
</blockquote>
<p>
Note that <code>getPassword</code> returns a character array.
Password information should not be stored or passed around in
strings because strings are not secure.
So don't [PENDING: or you can't] use
<code>getText</code> or <code>setText</code> on a password field.
Instead use <code>getPassword</code> or <code>setPassword</code>
because these methods use character arrays instead of strings.
</blockquote>
<a name="apitables">
<h4>The Text Field API</h4>
</a>
<blockquote>
[PENDING: I need to revisit these to make sure that
I haven't left anything out from the parental classes]
<p>
The following tables list the commonly used
<code>JTextField</code> constructors and methods.
Other methods you're likely to call
are defined by the
<a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.JComponent.html"><code>JComponent</code></a><a target="_top" href="http://java.sun.com/products/jfc/swingdoc-api/com.sun.java.swing.JComponent.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a> and
<a target="_top" href="http://java.sun.com/products/jdk/1.1/api/java.awt.Component.html"><code>Component</code></a><a target="_top" href="http://java.sun.com/products/jdk/1.1/api/java.awt.Component.html"><img src="../../images/apiIcon.gif" width=20 height=20 border=0 alt="(in the API reference documentation)"></a> classes.
They include <code>Component</code>'s
<code>setForeground</code>,
<code>setBackground</code>,
and
<code>setFont</code>
methods.
[CHECK: is that right? any other particularly useful Component/JComponent
methods?]
[Link to JComponent and Component discussions.]
<p>
The API for using text fields falls into three categories:
<ul>
<li><a href="#contents">Setting or Getting the Text Field's Contents</a>
<li><a href="#looks">Fine Tuning the Text Field's Appearance</a>
<li><a href="#events">Handling Events from a Text Field</a>
</ul>
<p>
<table border=1>
<caption><a name="contents">Setting or Getting the Text Field's Contents</a></caption>
<tr>
<th>Method or Constructor
<th>Purpose
<tr>
<td><font size=2><code>
<br>
JTextField()
<br>
JTextField(String)
<br>
JTextField(String, int)
<br>
JTextField(int)
<br>
JTextField(Document, String, int)</code>
<td>Create a <code>JTextField</code> instance,
initializing it to contain the specified text.
The <code>int</code> argument sets the number of columns.
This is used to compute the component's preferred width
and may not be the actual number of columns displayed [CHECK].
<tr>
<td><font size=2><code>void setText(String)
<br>
String getText()</code></font>
<td>Set or get the text displayed by the text field.
</table>
<p>
<table border=1>
<caption><a name="looks">Fine Tuning the Text Field's Appearance</a></caption>
<tr>
<th>Method or Constructor
<th>Purpose
<tr>
<td><font size=2><code>void setEditable(boolean)
<br>
boolean isEditable()
</code></font>
<td>Set or get whether the user can edit the text in the text field.
<tr>
<td><font size=2><code>void setForeground(Color)
<br>
Color getForeground()
</code></font>
<td>Set or get the color of the text within the text field.
<tr>
<td><font size=2><code>void setBackground(Color);
<br>
Color getBackground()
</code></font>
<td>Set or get the background color of the text field.
<tr>
<td><font size=2><code>void setFont(Font);
<br>
Font getFont()
</code></font>
<td>Set or get the font used by the text field.
<tr>
<td><font size=2><code>void setHorizontalAlignment(int);
<br>
int getHorizontalAlignment()
</code></font>
<td>Set or get how the text is aligned horizontally within its area.
You can use <code>JTextField.LEFT</code>, <code>JTextField.CENTER</code>,
and <code>JTextField.RIGHT</code> for arguments.
</table>
<p>
<table border=1>
<caption><a name="events">Handling Events from a Text Field</a></caption>
<tr>
<th>Method or Constructor
<th>Purpose
<tr>
<td><font size=2><code>addActionListener(ActionListener)
</code></font>
<td>Provide the text field with an ActionListener.
</table>
</blockquote>
<a name="examples">
<h4>Examples that Use Text Fields</h4>
</a>
<blockquote>
This table shows the examples that use <code>JTextField</code>
and where those examples are described.
<p>
<table>
<tr>
<th align=left> Example
<th align=left> Where Described
<th align=left> Notes
<tr>
<td> <a href="example-swing/TextDemo.java"><code>TextDemo.java</code></a>
<td> This page.
<td> Uses a text field with an action listener.
<tr>
<td> <a href="example-swing/TextFieldDemo.java"><code>TextFieldDemo.java</code></a>
<td> This page.
<td> Implements two different keystroke-validated fields.
<tr>
<td> <a href="example-swing/PasswordDemo.java"><code>PasswordDemo.java</code></a>
<td> This page and
<a href="threads.html#SwingWorker">Using the SwingWorkerClass</a>
<td> Uses a <code>JPasswordField</code>.
<tr>
<td> <a href="../../together/bingo/example-swing/bingo/player/ControlPane.java"><code>ControlPane.java</code></a>,
<a href="../../together/bingo/example-swing/bingo/shared/Utilities.java"><code>Utilities.java</code></a>
<td>
<a target="_top" href="../../together/bingo/letsplay.html">Let's Play</a><a target="_top" href="../../together/bingo/letsplay.html"><img src="../../images/jdk1_1.gif" width=20 height=20 border=0 alt="(in Putting It Together trail)"></a><td> Uses a grid bag layout to align labels with text fields.
See the <code>addParameterRow</code> method
in <a
href="../../together/bingo/example-swing/bingo/shared/Utilities.java"><code>Utilities.java</code></a>.
Part of the BINGO player application.
<tr>
<td> <a href="example-swing/CustomDialog.java"><code>CustomDialog.java</code></a>
<td> <a href="dialog.html">How to Make Dialogs</a>
<td> Includes a text field whose value is checked.
Part of DialogDemo (under the More Dialogs tab).
</table>
</blockquote>
</blockquote>
<p>
<hr size=4>
<p>
<table width="100%">
<tr>
<td align=left>
<a href="text.html"><img src="../../images/PreviousArrow.gif" width=26 height=26 align=top border=0 alt="Previous | "></a><a
href="toolbar.html"><img src="../../images/NextArrow.gif" width=26 height=26 align=top border=0 alt="Next | "></a><a
href="../../trailmap.html"><img src="../../images/WayUpArrow.gif" width=26 height=26 align=top border=0 alt="Trail Map | "></a><a
href="../index.html"><img src="../../images/uiHeader.gif" width=26 height=26 align=top border=0 alt="Creating a User Interface | "></a>
</td>
<td align=right>
<a href="index.html"><strong><em>Using the JFC/Swing Packages</em></strong></a>
</td>
</tr>
</table>
</body>
</html>
--------------B2865773E58F282F8BE3297C
Content-Type: text/x-vcard; charset=koi8-r;
name="acidsteve.vcf"
Content-Transfer-Encoding: 7bit
Content-Description: Card for Vladimir Olenin
Content-Disposition: attachment;
filename="acidsteve.vcf"
begin:vcard
n:Olenin;Vladimir
x-mozilla-html:FALSE
org:
adr:
version:2.1
email;internet:acidsteve@hempseed.com
title:Card
note:Java programmer. Open for projects development offers.
fn:Vladimir Olenin
end:vcard
--------------B2865773E58F282F8BE3297C--
Technical Details
Message-ID:
<35E86D0B.7FB0E906@hempseed.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<6rs61v$e8916@forums.borland.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 111d45,4172dc4641d32d13 X-Google-Attributes: gid111d45,public From: Vladimir Olenin <acidsteve@hempseed.com> Subject: Re: Prevent further input once x # of chars entered into a JTextField Date: 1998/08/30 Message-ID: <35E86D0B.7FB0E906@hempseed.com> X-Deja-AN: 385984269 References: <6rs61v$e8916@forums.borland.com> X-Accept-Language: ru Content-Type: multipart/mixed; boundary="------------B2865773E58F282F8BE3297C" Organization: Another Netscape Collabra Server User Mime-Version: 1.0 Newsgroups: borland.public.jbuilder.java.swing