Está en la página 1de 45

Text Management

27/09/06

JTextFields
JComponent JTextComponent JTextField JPasswordField

Single line of text Usually used for simple data entry, may be used as labels if you disable editing UNICODE compliant Supports
Text selection Clipboard operations

Supports keyboard mnemonics


No support in original AWT Alt-key combination

27/09/06

JTextField and JPasswordField

JTextField Constructors
JTextField() JTextField(String text) JTextField(int columns)
Columns in JTextField are based on lower case ms in the current font Does not limit input length

JTextField(String text, int columns) JTextField(Document doc, String text, int columns)
Uses the chosen document model.

JPasswordField Constructors
same arglist as JTextField

JPasswordField methods

public char getEchoChar() public void setEchoChar(char c) public boolean echoCharIsSet() Be aware that Java bytecode may pose significant problems when validating passwords. The JPasswordField is merely a JTextField with empty characters echoed back to the window.
3

27/09/06

JTextField and JPasswordField methods


Methods specific to JTextField
public void setColumns(int columns)
Based on the m character of the current font

public void setFont(Font f) public void setHorizontalAlignment(int alignment)


LEFT, CENTER, or RIGHT

public void scrollRectToVisible(Rectangle r) public Action[] getActions() protected Document createDefaultModel() public setScrollOffset(int offset)
Number of pixels of the text string which are out of view to the let of the controls visible area

From JTextComponent
public void setEditable(boolean canEdit)

27/09/06

Code Example MyJTextField.java

27/09/06

Text fields and the Input Focus


Using the TAB key to move to a field can be a bit annoying But, there is not text automatically associated with a JTextField
Typically use JLabels

One way to do it is pretend the JLabel is the target of the accelerator, but in fact the JTextField is the target
Use the setDisplayedMnemonic() method for JLabel

Code Example, TextAcceleratorExample.java

27/09/06

More on Text fields and Input Focus


Code Example, TextAcceleratorExample2.java Second method to link labels to text fields
Visual cue is obtained by setting a mnemonic on each label using
setDisplayedMnemonic()

Note that setFocusAccelerator() is now commented out Use setLabelFor(Component c) method to link JLabel to component When mnemonic activated for JLabel, it will pass the focus to the component given to it by setLabelFor()

27/09/06

Default Key Bindings


JTextField, like all Text Components, has a set of default key bindings already in place

Operation Copy Cut Paste

Java CTRL+c CTRL+x CTRL+v

Windows CTRL+c CTRL+x CTRL+v

Motif CTRL+INSERT SHIFT+DELETE SHIFT+INSERT

27/09/06

Code Example, MyPasswordField.java

27/09/06

Using JTextFields
A text field is a basic text control that lets the user type in a small amount of text and fires an action event when the user indicates that text entry is complete (usually by pressing Return). To validate an entry in a text field
Container-validated Action-validated Keystroke-validated. Focus-validated Combination of the above (JFormattedTextField)

27/09/06

10

Container Validation
Sometimes the best way Monitor the closing or completion of a GUI screen and check all values then Think about all of the ways you can leave a panel
Window Closing OK/Cancel Leave tabbed pane Hide window Change of focus

27/09/06

11

Action Validation
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 actionvalidated 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 actionPerformed method as follows:
Use getText to get the contents of the text field. Evaluate the value returned by getText. 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.

27/09/06

12

Keystroke Validated Entry


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 change (keystroke, cut, copy, and so on) that causes the data to be invalid is rejected. You could catch each keystroke, but that is difficult and inefficient and how do you catch data entered with cut-and-paste actions Two ways to do Keystroke Validated Entry
Use JDK 1.4 JFormattedTextField Create a custon document for your text field.
Do not use a document listener 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, and you generate a new event as you undo the change.. Subclass JTextField an override the createDefaultModel() method to return your own version of a PlainDocument object

27/09/06

13

JDK 1.4 JFormattedTextField


Similar in many ways to a custom example found later in this section. JFormattedTextField adds support for formatting arbitrary values, as well as retrieving a particular object once the user has edited the text. The following illustrates configuring a JFormattedTextField to edit dates:
JFormattedTextField ftf = new JFormattedTextField(); ftf.setValue(new Date());

You can listen for editing changes by way of adding a PropertyChangeListener and listening for change events named value.

27/09/06

14

New Focus Features


JFormattedTextField has the unique feature of allowing you to control what happens when focus is lost: The possible configurations are:
revert to the last value: (JFormattedTextField.RevertValueOnFocusLost). commit the edit (JFormattedTextField.CommitValueOnFocusLost), if commiting the edit fails, that is a ParseException is thrown, you can specify if the value should be reverted (JFormattedTextField.CommitOrRevertValueOnFocusLost). Lastly, you can specify that nothing should happen (JFormattedTextField.PersistValueOnFocusLost). The default is (JFormattedTextField.CommitOrRevertValueOnFocusLost).

27/09/06

15

Locking Focus
To lock the focus down while the JFormattedTextField is an invalid edit state you can attach an InputVerifier.
public class FormattedTextFieldVerifier extends InputVerifier { public boolean verify(JComponent input) { if (input instanceof JFormattedTextField) { JFormattedTextField ftf = (JFormattedTextField)input; AbstractFormatter formatter = ftf.getFormatter(); if (formatter != null) { String text = ftf.getText(); try { formatter.stringToValue(text); return true; } catch (ParseException pe) { return false; } } } return true; } public boolean shouldYieldFocus(JComponent input) { return verify(input); } }

27/09/06

16

Formatting the JFormattedTextField


Formatting is actually done through an instance of JFormattedTextField.AbstractFormatter which is obtained from an instance of JFormattedTextField.AbstractFormatterFactory. JFormattedTextField typically queries the AbstractFormatterFactory for an AbstractFormat when it gains or loses focus. Although this can change based on the focus lost policy.
If the focus lost policy is JFormattedTextField.PersistValueOnFocusLost and the JFormattedTextField has been edited, the AbstractFormatterFactory will not be queried until the value has been commited. Similarly if the focus lost policy is JFormattedTextField.CommitValueOnFocusLost and an exception is thrown from stringToValue, the AbstractFormatterFactory will not be queried when focus is lost or gained.

You can force the current value to be obtained from the current JFormattedTextField.AbstractFormatter by way of invoking commitEdit. commitEdit will be invoked whenever return is pressed in the JFormattedTextField.

27/09/06

17

Choosing the Formatter


If an AbstractFormatterFactory has not been explicitly set, one will be set based on the Class of the value type after setValue has been invoked (assuming value is non-null). For example, in the following code an appropriate AbstractFormatterFactory and AbstractFormatter will be created to handle formatting of numbers:
JFormattedTextField tf = new FormattedTextField(); tf.setValue(new Number(100));

27/09/06

18

Sample Code, MyJFormattedTextField.java

27/09/06

19

Masked Text Fields


Allows you to quickly make input masks
Bounded range Limit character types

Code Example MaskFormatterExample.java

27/09/06

20

Using a Custom Document Model


The idea is to catch all input into the model, and check it then You do this by overriding the insertString() and removeString() methods to check the incoming string, then call super.insertString() What if you wanted to limit the number of characters you could type into a JTextField?
Code Example, BoundedTextField.java, BoundedPlainDocument.java

27/09/06

21

Code Example,ValidatedTextField.java

27/09/06

22

Entering and checking Formatted Numeric Data


You could use a Decimal Format object for output into a JTextField
#,###.## would give 1,000.00 as output to a string Each # represents a digit

But insertString should:


Merge the text being inserted with that already in the model Parse the resulting text using the models DecimalFormat object If it is not valid reject it If it is valid, insert it in the model
this may occur after being formatted/rounded to the DecimalFormat objects format

Code Example NumericTextField.java, NumericPlainDocument.java

27/09/06

23

Document Listener on a Text Field


If you dont use a DocumentListener on a Text Field to check input what is it used for? Use it to listen to, but not interfere with, changes to the document's content
Log changes React to entries by affecting another object

Methods
void changedUpdate(DocumentEvent e)
Gives notification that an attribute or set of attributes changed.

void insertUpdate(DocumentEvent e)
Gives notification that there was an insert into the document.

void removeUpdate(DocumentEvent e)
Gives notification that a portion of the document has been removed

27/09/06

24

Setting Mnemonics for JTextFields


If a JTextField does not contain a text label, how do you set mnemonics for it? Two ways
setDisplayedMnemonic()
Set a displayed mnemonic on a JLabel Set the focus accelerator for that letter on the JTextField.

setLabelFor()
Set a displayed mnemonic on a JLabel

27/09/06

25

Sample Code, Mnemonic.java

27/09/06

26

JTextComponent
So far, most JComponents covered have had very simple input and output event handling
Mostly dealing with ActionListeners for Buttons

JTextComponent provides basic functionality found in most text input objects Initial Text support in AWT was limited
Single font in a window No embedded graphics
JComponent JTextComponent JTextArea

JTextField JEditorPane

JPasswordField

27/09/06

27

Requirements for JTextComponent


Support previous AWT API as much as possible, minimizing porting problems Provide a set of components capable of interacting with the native OS to support operations like direct manipulation (drag and drop) and clipboard operations. Support formats beyond plain text (HTML, RTF) Support Swings pluggable look-and-feel capabilities Note that one significant change from AWT to Swing Text components is the change from TextEvent and TextListener to DocumentEvent and DocumentListener

27/09/06

28

JTextComponent components
JTextComponent is the foundation for Swing's text components, and provides these customizable features for all of its descendants:
A separate model, known as a document, to manage the component's content. A separate view, which is in charge of displaying the component on screen. A separate controller, known as an editor kit, that can read and write text and implements editing capabilities with action commands. Customizable keymaps and key bindings. Support for infinite undo/redo. Pluggable caret and support for caret change listeners.

27/09/06

29

JTextComponent and MVC


Like many other Swing components, a text component separates its content from its view.

27/09/06

30

JTextComponent features
Clipboard operations
textComponent.copy() textComponent.cut() textComponent.paste()

Work on any Swing text component

Save/Load operations
Direct input/output to stream using JTextComponent Stream may be local file or URL
textComponent.read(xcReadStream, http://www.mysite.com) textComponent.read(xcStreamStream)

27/09/06

31

JTextComponent significant methods


Has separate model, known as a document, to manage the component's content. Every JTextComponent has an associated Document.
public void setDocument(Document doc) public Document getDocument

Text operations
public public public public public void setText(String t) void getText() String getSelectedText() void replaceSelection(String content) String getText(int offset, int length) throws BadLocationException

Move caret
public public public public public Caret getCaret() void setCaret(Caret c) void setCaretPosition(int position) int getCaretPosition() void moveCaretPosition()

27/09/06

32

JTextComponent significant methods continued


Swing supports a Highlighter object for text You can set colors for Caret, Selection, SelectedText, DisabledText Text selection is a very important feature of the text component class hierarchy. These methods allow developers to programmatically select regions of text within the document

27/09/06

33

Document handling
In AWT, text was contained by several different types of objects, and TextListener and TextEvent classes watched for changes in that text. This proved to be limiting The Document class holds a document, but users of the Document class are responsible for displaying the contents Document is a Swing-based container used to hold text and to provide notifications of changes to such text.
Includes ability to mark-up(select text) Manage changes to text

In JDK 1.4, if JTextComponent does not have a Tooltip Text associated, the view under the mouse will be asked to provide one
If the View corresponds to an HTML element with an ALT attribute, then the tooltip text will be the value of that attribute.

27/09/06

34

Document internal element structure


Typically contains only a single element structure, but supports several Base unit of containment called an element Each element includes an arbitrary set of attributes associated with its text

27/09/06

35

Document structure
Code Example, PlainTextModel.java

27/09/06

36

Document class
selecting text
public abstract String getText(int offset, int length) throws BadLocationException public abstract void getText(int offset, int length, Segment text) throws BadLocationException public abstract void insertString(int offset, String str, AttributeSet a) throws BadLocationException public abstract void remove(int offset, int length) throws BadLocationException

Get number of characters in document


public abstract int getLength()

Assign listeners to monitor changes in document


public abstract void addDocumentListener(DocumentListener listener) public abstract void removeDocumentListener(DocumentListener listener)
27/09/06 37

Document class continued


Used to mark change locations in document
public abstract Position getStartPosition() public abstract Position getEndPosition() public abstract Position createPosition(int offset) throws BadLocationException

Get/set properties
public abstract Object getProperty(Object key) public abstract void putProperty(Object key, Object value)

Manage root elements


public abstract Element[] getRootElements() public abstract Element getDefaultRootElement()

Renderer for model


public abstract void render(Runnable r)

27/09/06

38

DocumentListener
A DocumentListener interface is designed to watch for changes in a document and react to them. You should never modify the contents of text component from within a document listener. If you attempt to modify the text in a text component from within a document listener, your program will likely deadlock!

27/09/06

39

Editor Kits
It is the editor kit that provides the code that actually inserts new content in a document, deletes characters, moves the cursor, allows the user to cut and paste etc All Swing text components supports standard editing commands such as cut, copy, paste, and inserting characters. Each editing command is represented and implemented by an action object.
The set of actions that an editor provides can be determined by calling its getActions() method

This makes it easy for you to associate a command with a GUI component, such as a menu item or button, and build a GUI around a text component. Under the hood, a text component uses an EditorKit object to create and manage its actions. Editor Kits supplied by JDK
27/09/06

DefaultEditorKit, StyledEditorKit, and HTMLEditorKit

40

Ways to retrieve model content


You can get entire content from a model with the getText() method, or even substrings with getText(int, int) Not necessarily the most efficient There is a Segment object
public class Segment { public char[] array; public int offset; public int count; public Segment(); public Segment(char [], int, int) public String toString() }

There is a getText(int, int, Segment) call which sets the array, offset, and count members to point to a char array that contains data in the specified range. In some cases the char[] will point to the original data, so dont modify text in a segment
27/09/06 41

Positions in a document
Although the insertString remove, and getText methods use absolute offsets to specify locations within the model, you often want some relative ones.
Supports the change of content within the model If you have a pointer to the beginning of the text, and new is inserted into it, the start position is no longer valid.

Positions objects are used by the model.


Tied to a particular offset in the model that is specified when the createPosition() method is called. Remains attached to the location even if its offset changes later
Position paraPos = model.createPosition(50); System.out.println(Initial offset = + paraPos.getOffset()); model.remove(10, 20); System.out.println(Final offset = + paraPos.getOffset());

27/09/06

42

Implementing Custom Views


The View displays the data from the model on the screen By creating a new View that renders the content of a text field in a particular way you can customize a components
Each View needs a ViewFactory that will create instances of it as appropriate This is provided by a text components editor kit, or by its UI delegate class

We can subclass JTextField to display formatting characters around data


(443)778-5756 (***)***-**** mask field: Whever the * character appears in the mask field, the corresponding character in the format string will be replaced with the character from the model ()-. Format field: characters that correspond to the * fields are just filler if no data exists
27/09/06 43

Code Example, FormattedTextField.java , FormattedTextView.java, BoundedPlainDocument.java, and FormattedTextFieldUI.java

27/09/06

44

Drag and Drop


In JDK 1.4, JTextComponent has a setDragEnabled(booleanb) method
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. Default value of the dragEnabled property is false. When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over a selection and then moves the mouse a few pixels. Some look and feels might not support automatic drag and drop; they will ignore this property.

27/09/06

45

También podría gustarte