这个压缩包里的都是超级经典的java例子
源代码在线查看: createcmd.htm
Creating a Custom Editing Command for a JTextComponent (Java Developers Almanac Example)
The Java Developers Almanac 1.4
Order this book from Amazon.
google_ad_client = "pub-6001183370374757";
google_ad_width = 120;
google_ad_height = 600;
google_ad_format = "120x600_as";
google_ad_channel = "4777242811";
google_ad_type = "text_image";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "6666CC";
google_color_url = "6666CC";
google_color_text = "000000";
//-->
Home
>
List of Packages
>
javax.swing.text
[49 examples]
>
Actions and Key Bindings
[5 examples]
e1002. Creating a Custom Editing Command for a JTextComponent
This example demonstrates how to implement an editing command.
There are two steps when creating a custom command.
The first is to create an action object that executes the
desired functionality and then installs the action object
in the component. The second is to bind a keystroke to the action
object using an inputmap.
Text component actions should extend from TextAction.
TextAction has a convenience method for finding the appropriate
text component on which to operate.
This example implements a Lowercase command that converts
characters to lowercase. If the selection is empty, the command
converts the character following the caret and then moves the caret
forward one space. If the selection is not empty, the command
converts the characters in the selection.
JTextArea comp = new JTextArea();
// Bind F2 to the lowercase action
String actionName = "Lowercase";
comp.getInputMap().put(KeyStroke.getKeyStroke("F2"), actionName);
// Install the action
comp.getActionMap().put(actionName,
new TextAction(actionName) {
public void actionPerformed(ActionEvent evt) {
lowercaseSelection(getTextComponent(evt));
}
}
);
public static void lowercaseSelection(JTextComponent comp) {
if (comp.getSelectionStart() == comp.getSelectionEnd()) {
// There is no selection, only a caret
if (comp.getCaretPosition() < comp.getDocument().getLength()) {
// The caret must be at least one position left of the end
try {
int pos = comp.getCaretPosition();
Document doc = comp.getDocument();
String str = doc.getText(pos, 1).toLowerCase();
doc.remove(pos, 1);
doc.insertString(pos, str, null);
comp.moveCaretPosition(pos+1);
} catch (BadLocationException e) {
}
}
} else {
// There is a selection
int s = comp.getSelectionStart();
int e = comp.getSelectionEnd();
comp.replaceSelection(comp.getSelectedText().toLowerCase());
comp.select(s, e);
}
}
Related Examples
e1001.
Overriding the Default Action of a JTextComponent
e1003.
Overriding a Few Default Typed Key Bindings in a JTextComponent
e1004.
Overriding Many Default Typed Key Bindings in a JTextComponent
e1005.
Listing the Key Bindings in a JTextComponent Keymap
See also:
Caret and Selection
Events
JEditorPane
JFormattedTextField
JTextArea
JTextComponent
JTextField
JTextPane
Styles
© 2002 Addison-Wesley.